udp多线程 java_多线程以从多个UDP客户端接收数据

该博客讨论如何在Java中实现一个多线程UDP服务器,以处理来自多个固定客户端(每个有5个预定义端口)的并发数据接收。内容涉及到如何为每个客户端的端口创建单独的接收线程,并探讨了在数据包丢失情况下跟踪和重新请求数据的策略。
摘要由CSDN通过智能技术生成

我想从不同的客户端接收数据(客户端数量是固定的,比如10),并且每个客户端在5个不同的预定义端口上发送数据,这些端口不会改变 . (例如,客户端1端口5000,5001,5002等) . 所有客户端都可以同时发送数据 . (以上都是固定的)

在TCP中说,我可以为我们接受的每个连接创建多个线程,如下所示 . UDP is connectionless,So how can we create one thread per UDP client(UDP port) to handle the concurrent data?Like each thread having a receivefrom() function to get data.

// UDP服务器

#define BUFLEN 512

#define CLIENT1_PORT1 5000

#define CLIENT1_PORT2 5001

#define CLIENT1_PORT3 5002

#define CLIENT2_PORT1 5050

#define CLIENT2_PORT2 5051

#define CLIENT2_PORT3 5052

#define CLIENT3_PORT1 6000

#define CLIENT3_PORT2 6001

#define CLIENT3_PORT3 6002

void diep(char *s) {

perror(s);

exit(1);

}

int main(void) {

struct sockaddr_in client1_sockaddr_1, client1_sockaddr_2,client2_sockaddr_1,client2_sockaddr_2, si_other;

int c1_sockfd_1,c1_sockfd_2, c2_sockfd_1,c2_sockfd_2, i, slen = sizeof(si_other);

char buf[BUFLEN];

/******for client 1 port1 **********/

if((c1_sockfd_1 = socket(AF_INET, SOCK_DGRAM, 0)) == -1)

diep("socket");

memset((char *) &client1_sockaddr_1, 0, sizeof(client1_sockaddr_1));

client1_sockaddr_1.sin_family = AF_INET;

client1_sockaddr_1.sin_port = htons(CLIENT1_PORT1);

client1_sockaddr_1.sin_addr.s_addr = htonl(INADDR_ANY);

if(bind(c1_sockfd_1, (struct sockaddr *) &client1_sockaddr_1, sizeof(client1_sockaddr_1)) == -1)

diep("bind");

if((c2_sockfd_1 = socket(AF_INET, SOCK_DGRAM, 0)) == -1)

diep("socket");

/*******for client 2 port1 *******/

memset((char *) &client2_sockaddr_1, 0, sizeof(client2_sockaddr_1));

client2_sockaddr_1.sin_family = AF_INET;

client2_sockaddr_1.sin_port = htons(CLIENT2_PORT1);

client2_sockaddr_1.sin_addr.s_addr = htonl(INADDR_ANY);

if(bind(c1_sockfd_2, (struct sockaddr *) &client2_sockaddr_1, sizeof(client2_sockaddr_1)) == -1)

diep("bind");

//Receive from clients

while(1) {

/*How to create threads at this point and have a separate recvfrom for each client port ??*/

if(recvfrom(c1_sockfd_1, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)

diep("recvfrom()");

printf("Recieved packet from %s: %d\nData: %s\n\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);

}

close(c1_sockfd_1);

return 0;

}

Update 我每个客户端有5个端口,总共5 * 10个插槽,数据将在几毫秒的时间间隔内同时发送 . 每个端口收到的数据包大小不同 . 数据包与Header和CRC一起发送 . 为了跟踪和重新请求丢失的数据包,有一个包号是一个好主意吗?

(或)跟踪丢失的数据包并使用UDP请求它们的不同方法有哪些?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值