来一个最简单的TCP服务器

本文介绍了一个简单的TCP服务器实现过程,该服务器使用C语言编写,并利用socket编程完成客户端连接的接收及消息读取。但该服务器存在明显局限性,即同一时间只能处理一个连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1 #include<stdio.h>
  2 #include<sys/types.h>
  3 #include<sys/socket.h>
  4 #include<stdlib.h>
  5 #include<netinet/in.h>
  6 #include<errno.h>
  7 
  8 
  9 
 10 int init(const char* ip,int port)
 11 {
 12     int sock = socket(AF_INET,SOCK_STREAM,0);
 13     if(sock< 0)
 14     {
 15         perror("socket\n");
 16         exit(2);
 17     }
 18 
 19     struct sockaddr_in local;
 20     local.sin_family = AF_INET;
 21     local.sin_port = htons(port);
 22     local.sin_addr.s_addr = inet_addr(ip);
 23 
 24     if(bind(sock, (struct sockaddr*)&local, sizeof(local) )<0)
 25     {
 26         perror("bind ");
 27         exit(3);
 28     }
 29     if(listen(sock , 5)<0)
 30     {
 31         perror("listen");
 32     }
 33     return sock;
 34 }
 35 
 36 
 37 int main(int argc,char* argv[])
 38 { 
 39     if(argc != 3)
 40     {
 41         printf("use: [ip] [port]\n");
 42         exit(1);
 43     }
 44     int sock = init(argv[1],atoi(argv[2]));
 45     struct sockaddr_in remote;
 46     int len =sizeof(remote);
 47     while(1)
 48     {
 49         int new_fd = accept(sock ,(struct sockaddr*)&remote , 

&len );
 50         char buf[1024];
 51         printf("get a new connect:%s %d\n",inet_ntoa

(remote.sin_addr.s_addr),ntohs(remote.sin_port));
 52         if(new_fd >0)
 53         {
 54 
 55             while(1)
 56             {
 57                 if(new_fd >0)
 58                 {
 59                     ssize_t s = read(new_fd,buf,sizeof(buf));
 60                     if( s > 0)
 61                     {
 62                         buf[s] = 0;
 63                         printf("client: %s\n",buf);
 64                     }
 65                     else if(s ==0 )
 66                     {
 67                         printf("connect closed \n");
 68                         break;
 69                     }
 70                     else
 71                     {
 72 
 73                         perror("read...\n");
 74                         break;
 75                     }
 76                 }
 77             }
 78         }
 79     }
 80 return 0;
 81 }


写着玩的。
最大最大的缺点:同一时间只能有一个连接。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值