- TCP服务器的实现流程:
- 一、创建套接字(socket函数):
- 通信域选择IPV4网络协议、套接字类型选择流式;
int sockfd = socket(AF_INET,SOCK_STREAM,0);
- 二、填充服务器的网络信息结构体:
- 1.定义网络信息结构体变量;
- 2.求出结构体变量的内存空间大小;
- 3.结构体清零;
- 4.使用IPV4网络协议;
- 5.预留给在终端输入的网络字节序的端口号;
- 6.预留给在终端输入的IP地址;
struct sockaddr_in serveraddr;
socklen_t serveraddrlen = sizeof(serveraddr);
memset(&serveraddr,0,serveraddrlen);
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port = htons(atoi(argv[2]));
- 三、套接字和服务器的网络信息结构体进行绑定(bind函数):
int ret = bind(sockfd,(struct sockaddr *)&serveraddr,serveraddrlen);
int ret1 = listen(sockfd, 5);
int acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientaddr_len);
- 六、接收来自客户端的数据(recv函数)和给客户端发送应答消息(send函数):
int nbytes = recv(acceptfd,buf,sizeof(buf),0);
printf("客户端发来数据[%s]\n",buf);
strcat(buf,"----k");
int ret2 = send(acceptfd,buf,sizeof(buf),0);
close(acceptfd);
close(sockfd);
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ERRLOG(msg) do{\
printf("%s:%s:%d\n", __FILE__, __func__, __LINE__);\
perror(msg);\
exit(-1);\
}while(0)
int main(int argc, char const *argv[])
{
if(3 != argc)
{
printf("Usage : %s \n",argv[0]);
exit(-1);
}
int sockfd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == sockfd)
{
ERRLOG("socket error");
}
printf("sockfd = %d\n",sockfd);
struct sockaddr_in serveraddr;
socklen_t serveraddrlen = sizeof(serveraddr);
memset(&serveraddr,0,serveraddrlen);
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port = htons(atoi(argv[2]));
if(-1 == bind(sockfd,(struct sockaddr *)&serveraddr,serveraddrlen))
{
ERRLOG("bind error");
}
if(-1 == listen(sockfd,5))
{
ERRLOG("listen error");
}
struct sockaddr_in clientaddr;
memset(&clientaddr,0,sizeof(clientaddr));
socklen_t clientaddr_len = sizeof(clientaddr);
int acceptfd = 0;
char buf[128] = {0};
int nbytes = 0;
while(1)
{
printf("正在等待客户机连接服务器\n");
if(-1 == (acceptfd = accept(sockfd,(struct sockaddr *)&clientaddr,&clientaddr_len)))
{
ERRLOG("accept error");
}
printf("客户端[%s:%d]连接到了服务器\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port));
while(1)
{
memset(buf,0,sizeof(buf));
if(-1 == (nbytes = recv(acceptfd,buf,128,0)))
{
ERRLOG("recv error");
}else if(0 == nbytes){
printf("客户端[%s:%d]断开了服务器\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port));
break;
}
if(!strncmp(buf,"quit",4))
{
printf("客户端[%s:%d]退出了\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port));
break;
}
printf("客户端[%s:%d]发来数据[%s]\n",inet_ntoa(clientaddr.sin_addr),ntohs(clientaddr.sin_port),buf);
strcat(buf,"----k");
if(-1 == send(acceptfd,buf,sizeof(buf),0))
{
ERRLOG("send error");
}
}
close(acceptfd);
}
close(sockfd);
return 0;
}