简体   繁体   中英

Handling Multiple threads with TCP

I am trying to implement a chat application, and have a design choice to make about using TCP or UDP for the messaging exchange between peers. I want to use TCP but am having the following issue.

Problem Scenario: Peer A is listening on a well known port, (say 5555). When peer B wants to send message to peer A, it connects to the port 5555 on A. Peer A accepts the connection and starts a new thread to deal the communication with peer B, so that other peers (say peer C) are able to connect to peer A's 5555 port. Now the problem is that its not a request/response protocol, so I am confused that if peer A doesn't reply to peer B for any reason, then the subsequent messages sent by B will be delivered to port 5555 on peer A ? and peer A will create separate threads for each of the messages received ?

Using UDP will probably solve this problem and I wont have to create separate threads for communicating with each peer and everyone can send the messages to the same well known port. But I want to use TCP for guaranteeing that the messages will be delivered. Any ideas what would be a good way to handle this problem and use only one thread for communication with one peer ?

The problem you describe won't happen because TCP is a 'connected' protocol, which basically means that the two peers have to negotiate the communication before anything else can happen. After that, TCP controls the order of data packets to make sure they arrive at destination and in the right order. BTW, TCP stands for Transmission Control Protocol so it puts a lot of emphasis making sure what you described does not happen. It's not at all the case with UDP.

Once your ServerSocket has accepted the connection from the client Socket , the negotiation has been finalized and the TCP stream is dedicated to that communication.

The only way a new one is created is if your client emits another connect through a new Socket.

But the best way to convince yourself is to add logging to your app and try it yourself.

You are confusing listening , or server, sockets and connected sockets.

Once TCP connection is accepted on the listening side, you have a brand-new full-duplex socket between two parties, so they can exchange data. The only purpose of a listening socket is to accept connections, no application data flows through those.

You can hand that new connected socket off to a thread, but you certainly don't have to - you can handle many non-blocking sockets in a single thread, I believe Java NIO package was created for exactly this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM