linux网络编程之用多线程实现客户端到服务端的通信(基于udp)
【摘要】 1、开启一个线程接受数据,主线程发送数据的代码
#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <pthread.h>#include <netinet/in.h>#i...
1、开启一个线程接受数据,主线程发送数据的代码
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <netinet/in.h>
#include <errno.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>
//接收线程,负责消息并且显示
void *recv_thread(void* arg)
{
int udp_fd = (int)arg;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
socklen_t addrlen = sizeof(addr);
bzero(&addr, sizeof(addr));
while (1)
{
char buf[256] = "";
char ipbuf[256] = "";
recvfrom(udp_fd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen);
printf("\r\033[0:31m[%s]:\033[31m%s\n", inet_ntop(AF_INET, &addr.sin_addr, ipbuf, sizeo
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/60885348
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)