tcp通信过程 以获取服务器时间为例子

公共头文件

include

include

include

include

include

include

include

include

include

define MAX_LISTEN_QUE 5

server.c

include "socket_includes.h"

int main(int argc, char *argv[])
{
int listenfd, sockfd, opt = 1;
struct sockaddr_in server, client;
char buf[200];
socklen_t len;
time_t timep;
int ret;

listenfd = socket(AF_INET, SOCK_STREAM, 0);

if(listenfd < 0){
perror("Create socket fail.");
return -1;
}

if((ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) < 0){
    perror("Error, set socket reuse addr failed");  
    return -1;

}

bzero(&server, sizeof(server));

server.sin_family = AF_INET;
server.sin_port = htons(8888);
server.sin_addr.s_addr = htonl(INADDR_ANY);

len = sizeof(struct sockaddr);

if(bind(listenfd, (struct sockaddr *)&server, len)<0){
perror("bind error.");
return -1;
}

listen(listenfd, MAX_LISTEN_QUE);

while(1)
{
    sockfd = accept(listenfd, (struct sockaddr *)&client, &len);
  if(sockfd < 0){
            perror("accept error.");
            return -1;
  }
    timep = time(NULL);
    snprintf(buf, sizeof(buf), "%s", ctime(&timep));
    write(sockfd, buf, strlen(buf));
    printf("Bytes:%lu\n", strlen(buf));
    printf("sockfd=%d\n", sockfd);
    close(sockfd);
}
return 0;

}


include "socket_includes.h"

int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;
char buf[100];
int bytes;

if(( sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
{
    perror("socket error");
    return -1;
}

bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family     =       AF_INET;
servaddr.sin_addr.s_addr=       inet_addr("127.0.0.1");
servaddr.sin_port       =       htons(8888);

if( connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0 )
{
    perror("connect error");
    return 0;
}

bytes = read(sockfd, buf, 100);
if(bytes < 0){
    printf("Error, read failed.\n");
    return -1;
    }

if(0 == bytes){
    printf("Server close connection.\n");
    return -1;
    }

printf("Read bytes %d\n", bytes);
printf("Time:%s\n", buf);

close(sockfd);

}

你可能感兴趣的:(tcp通信过程 以获取服务器时间为例子)