Nurture passes nature.
教养胜过天性
udp的双向通信和TCP的大同小异,都是通过多线程进行收发,不同的就是本次例程只写了一份代码,如果在同一台虚拟机上跑一定要区分端口号。
直接上例程
udp_rdwr.c
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include <sys/select.h>
/* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
struct msg_info{
char name[256];
char msg[1024];
};
void *recv_thread(void *arg)
{
int udp_fd = *(int *)arg;
ssize_t recv_size;
struct msg_info msg;
struct sockaddr_in recv_addr;
socklen_t skt_len = sizeof(struct sockaddr_in);
while(1)
{
bzero(&msg, sizeof(msg));
recv_size = recvfrom

本文介绍了在Linux环境中,如何使用C/C++实现UDP的双向通信。内容涵盖关键函数如sendto、recvfrom、inet_aton、inet_ntoa、inet_addr、inet_pton和inet_ntop的使用,强调在相同主机上运行时需要注意端口号的区分。
最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



