简体   繁体   中英

How to dispatch send/receive data using C# socket tcp connection

I am writing socket client for IO device, which is the tcp server. I am able co connect and listen for data which the server periodically sends. But from time to time, I need to send some instruction to the server and read its response.

What is the proper way to handle this task, to be able listening for incoming data and after instruction is sent, receive response and to know, witch part of received data the response is?

What if device is sending data, while I need to send data to device? how can I dispatch such traffic? Do I need one thread to read and one for writing? Is it possible to handle this using single thread per device (there will be up to hundreds of devices connected)?

I am using Socket.Receive and Socket.Send methods.

What is the proper way to handle this task, to be able listening for incoming data and after instruction is sent, receive response and to know, witch part of received data the response is?

The protocol must support this. When you send data it is unclear when it is going to be received. The protocol must allow you to differentiate between normal data and a response. You could prepend a header to each message that has a boolean field indicating this.

What if device is sending data, while I need to send data to device?

You can send and receive on the same socket concurrently. This is not a problem. You would usually have on thread for reading. You can write on demand. No need for a thread dedicated to that.

there will be up to hundreds of devices connected

This means you need to have hundreds of reads outstanding. This is doable with one thread per socket. On the other hand this starts to be a good use case for async IO. Find out how to use async/await with sockets. If async/await is not available to you because you are on VS2010 use one of the other ways of achieving async IO with sockets.

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