开发者

Multiple sockets for clients to connect to

开发者 https://www.devze.com 2023-01-09 23:58 出处:网络
Is it possible to have multiple sockets, which can either by TCP or UDP in one program? For example: SocketOne: TCP socket at port 4567; socketTwo: TCP socket at port 8765; socketThree: UDP socket a

Is it possible to have multiple sockets, which can either by TCP or UDP in one program?

For example: SocketOne: TCP socket at port 4567; socketTwo: TCP socket at port 8765; socketThree: UDP socket at 7643.

The families will be AF_INET, and addresses will be INADDR_ANY for each.

I bind and listen for TCP, and just bind for UDP.

What makes me doubt being about to do this is, how do I wait for a client at each socket together.

I know that the code below won't work, but I don't know what else, or how to, e开发者_如何学JAVAxplain what I'm trying to say.

while (1)  
{   
    connected = accept(socketOne, (struct sockaddr *)&client_addr,&sin_size);

    connected = accept(socketTwo, (struct sockaddr *)&client_addr,&sin_size);

    bytes_read = recvfrom(socketThree,recv_data,1024,0,(struct sockaddr *)&client_addr, &addr_len);

}


You need the select function: http://linux.die.net/man/2/select

More user-friendly: http://beej.us/guide/bgnet/html/single/bgnet.html#select


man select.


There are a few real world examples of this. FTP has a control and data port which both use TCP and multimedia applications will use SIP or RTSP connections for control (TCP) and mulitple RTP and RTCP port (UDP) for each data stream received.

select or poll are used on unix and on Windows there are the OVERLAPPED apis to do this non-preemptively . Alternatively, this can be done with multiple threads.

0

精彩评论

暂无评论...
验证码 换一张
取 消