Chinaunix首页 | 论坛 | 博客
  • 博客访问: 956411
  • 博文数量: 120
  • 博客积分: 6454
  • 博客等级: 准将
  • 技术积分: 1739
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-28 17:45
文章分类

全部博文(120)

文章存档

2014年(1)

2013年(1)

2012年(11)

2011年(16)

2010年(6)

2009年(11)

2008年(30)

2007年(44)

分类: C/C++

2009-01-21 14:17:53


//#include

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int
main (int argc, char **argv)
{
    int fd = socket (AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        cout<<"socket() error: "<<errno<<endl;
        return -1;
    }
    else
        cout<<"socket() ok!"<<endl;
    struct sockaddr_in localaddr;
    localaddr.sin_family = AF_INET;
    localaddr.sin_addr.s_addr = htonl (INADDR_ANY);
    localaddr.sin_port = htons (5125);
    if (bind(fd, (struct sockaddr *)&localaddr, (socklen_t)sizeof(struct sockaddr_in)) == -1)
    {
        cout<<"bind() error\n";
        return -1;
    }
    else
        cout<<"bind() ok!\n";
    //if (listen (fd, SOMAXCONN) == -1)

    if (listen (fd, 2) == -1)
    {
        cout<<"listen() error\n";
        return -1;
    }
    else
        cout<<"listen ok! \n";
    char buf[1024];
    struct sockaddr_in remoteaddr;
    int client_sockfd;
    while (1)
    {
        socklen_t len = (socklen_t)sizeof(struct sockaddr);
        //client_sockfd = accept (fd, (struct sockaddr *) &remoteaddr, &len);

        client_sockfd = accept(fd, NULL, NULL);
        if (client_sockfd != -1)
        {
            cout<<"waiting for ...\n";
            int n = 0;
            while((n=recv(client_sockfd, buf, 1024, 0)) > 0)
            {
                buf[n] = '\0';
                cout<<"server read line: "<<buf<<endl;
                if(strcmp(buf, "reboot")==0)
                    cout<<"reboot!!!!!!!!!!!!!!!!!"<<endl;
            }
            close(client_sockfd);
            cout<<"close client"<<endl;
        }
        else
        {
            cout<<"accept() error!\n";
            break;
        }
    }
    close(fd);
    printf ("close client\n");

    return 0;
}

阅读(1816) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~