博客
关于我
socket多线程实现tcp server
阅读量:364 次
发布时间:2019-03-05

本文共 1077 字,大约阅读时间需要 3 分钟。

#include 
#include
#include
#include
#include
#include
#include
#include
#include
int InitSocket(){ int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) return -1; struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) return -1; if (listen(sockfd, 5) == -1) return -1; return sockfd;}void* fun(void* arg){ int c = (int) arg; while(1) { char buff[128] = {0}; if (recv(c, buff, 127, 0) <= 0) break; printf("recv(%d)=%s\n", c, buff); send(c, "ok", 2, 0); } printf("a client is connected(%d)\n", c); close(c);}int main(){ struct sockaddr_in caddr; int sockfd = InitSocket(); assert(sockfd != -1); while(1) { int len = sizeof(caddr); int c = accept(sockfd, (struct sockaddr *)&caddr, (size_t*)&len); if (c < 0) continue; printf("accept c=%d\n", c); pthread_t id; pthread_create(&id, NULL, fun, (void*)c); } close(sockfd); exit(0);}

转载地址:http://qklg.baihongyu.com/

你可能感兴趣的文章
Qt中的析构函数
查看>>
CSharp中委托(一)委托、匿名函数、lambda表达式、多播委托、窗体传值、泛型委托
查看>>
二叉堆的c++模板类实现
查看>>
C语言实现dijkstra(adjacence matrix)
查看>>
C#学习笔记(十四)事件(一)通知
查看>>
SQL Server SQL语句调优技巧
查看>>
用C#实现封装-徐新帅-专题视频课程
查看>>
C语言学习从初级到精通的疯狂实战教程-徐新帅-专题视频课程
查看>>
三层框架+sql server数据库 实战教学-徐新帅-专题视频课程
查看>>
NAT工作原理
查看>>
Processes, threads and goroutines
查看>>
c++中的10种常见继承
查看>>
E28 LoRa模块透传 定点传输 RSSI测试与MicroPython应用
查看>>
babel预设、插件和webpack中运行
查看>>
Vue学习—深入剖析渲染函数
查看>>
Vue学习—深入剖析函数式组件
查看>>
简单Makefile的编写
查看>>
使用BAT批处理 匹配查找指定文件夹,并在当文件夹下创建空文件
查看>>
wxpython的Hello,World代码探索
查看>>
【数字图像处理】OpenCV3 学习笔记
查看>>