简体   繁体   中英

How to read whenever there is an incoming message in Tcp socket programming in C#

I have a server-client program written in .NET C#. I have used socket programming and so far both the server and client are working. There is only one server instance, while I am able connect multiple clients all together. Right now my code works like the following scenario. 在此处输入图片说明

When I start the Server code, it starts Listening . When I start a client, it waits for a command to be written on the console. After I write something, the client sends that to the server, then the server does something with that, writes something back. This is how the cycle goes. Like a ping-pong game. My client code is availabe in this link .

Problem and what I want: With this functionality, my client cannot listen to the server unless it writes something to the server. I want to make it listen whenever there is an incoming message. My server code is fine and the sequence for server(listen then write) is okay. The client sequence(write the listen) is okay as well, but my client cannot read unless it writes. Suppose two clients are communicating with the server. client1 tells the server- "hey I need something that belongs to client2", then server will send a message to client2. With the current code, client2 cannot listen to the message because its actually waiting to write. Hope I made myself clear.

How can I achieve that? Any code samples will be helpful. Thank you.

You will need more than on thread on the client. One for accepting console input & sending and one for reading the TCP stream (blockingly) and displaying. Getting it to look like IRC on the console is a bit tricky because user written characters and received characters will interleave.

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