简体   繁体   中英

Two way communication across TCP clients

First of all, I'm wanting to play with this as a learning exercise, I'm not interested in other technologies like WCF :)

What I'm trying to do is have 2 applications, each running on a different machine that can talk to each other.

I have an example running where one app is the server and the other app the client. This works by using a TcpListener in the server app, which accepts a TCPClient, and then proceeds to read in a while loop, waiting for data from the TCPClient running in the client app.

This allows me to send data back and forth by reading/writing to the TCPClients stream in either app.

Although I can read/write both ways, its only the client that can ever instantiate an event , as its only the server that is waiting for something to happen. I'd like to extend this so that the client App also can receive messages instantiated from the server.

So am I right in thinking I'll need 2 TcpClients in each app? One used to send data, and the other always waiting for data?

As the two commenters have said, in this case you generally have the same app on both sides that acts as both client and server. As initial connection is usually started in response to user interaction (or some other external event), the normal pattern is to have all apps start in 'listen' mode (as a server). Once the a connection is requested on one app, it stops listening and tries to connect to others.

If the apps are to try to connect at start up, the simplest way is to do as above (all in server mode), and delay for a random time before swapping to client mode. If connection fails, drop back to server mode and delay again.

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