#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<errno.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<signal.h>
#define PORT 7777
int sockfd;
void server_exit(int sig)
{
if(sig == SIGINT)
shutdown(sockfd,SHUT_RDWR);
printf("server exit\n");
}
int main(int argc,char **argv)
{
/*1创建套接字 socket函数
2给套接字绑定ip地址和端口号:bind函数
3将套接字文件描述符,从主动变为被动文件描述符(做监听准备)listen函数
4被动监听客户的连接并响应:accept函数
5服务器调用read(recv)和write(send),收发数据,实现与客户的通信
6调用close或者shutdown关闭TCP的连接
*/
if(argc != 2)
{
printf("Please input ip addr:\n");
exit(1);
}
signal(SIGPIPE,SIG_IGN);
signal(SIGINT,SIG_IGN);
int cfd;
int r_n;
int w_n;
char message[1024];//定义一个缓冲区
socklen_t c_size;
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket error\n");
exit(1);
}
printf("socket successfully\n");
int opt=1;
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));//设置套接字可以重复使用端口号
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(PORT);
//s_addr.sin_addr.s_addr = inet_addr("192.168.91.248");
s_addr.sin_addr.s_addr = inet_addr(argv[1]);
//s_addr.sin_addr.s_addr = htons(INADDR_ANY);//绑定任意网卡。
if((bind(sockfd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in))!= 0))
{
perror("bind error\n");
exit(1);
}
printf("bind successfully\n");
if((listen(sockfd,20))!=0)
{
perror("listen error\n");
exit(1);
}
printf("listen successfully\n");
while(1)
{
c_size = sizeof(struct sockaddr_in);
cfd=accept(sockfd,(struct sockaddr *)&c_addr,&c_size);
//连接描述符,每连接一个客户端成功就生产一个描述符,只要知道这个描述符,就能与对应客户端通信
if(cfd<0)
{
perror("accept error\n");
exit(1);
}
printf("info client : ip = %s port = %d\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port));
//recv返回值为0,代表客户端退出
if((r_n=recv(cfd,message,sizeof(message)-1,0))<0)
{
perror("recv message error\n");
exit(1);
}
if(r_n==0)
{
printf("client is close\n");
}
else{
printf("client to msg :%s\n",message);
while(1)
{
memset(message,0,sizeof(message));
scanf("%s",message);
w_n=send(cfd,message,strlen(message),MSG_NOSIGNAL);
if(w_n<0)
{
perror("send data error\n");
//exit(1);
shutdown(cfd,SHUT_RDWR);
}
printf("send to msg successfully\n size=%d\n",w_n);
}
shutdown(cfd,SHUT_RDWR);
}
}
return 0;
}
TCP简单服务器的实现
于 2022-02-24 15:28:17 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)