简体   繁体   中英

TCPListener / TCPClient Server-Client Writing / Reading data

Here I am troubleshooting a theoretical problem about HOW servers and clients are working on machines. I know all NET Processes, but I am missing something referring to code. I was unable to find something related about this.

I code in Visual C# 2008, i use regular TCPClient / TCPListener with 2 different projects:

Project1 (Client)

Project2 (Server)

My issues are maybe so simple:

1-> About how server receives data, event handlers are possible? In my first server codes i used to make this loop:

while (true)
{

if (NetworkStream.DataAvailable)
    {
        //stuff
    }

Thread.Sleep(200);
}

I encounter this as a crap way to control the incoming data from a server. BUT server is always ready to receive data.

My question: There is anything like...? ->

AcceptTcpClient();

I want a handler that waits until something happen, in this case a specific socket data receiving.

2-> General networking I/O methods.

The problem is (beside I'm a noob) is how to handle multiple data writing. If I use to send a lot of data in a byte array, the sending can break if I send more data. All data got joined and errors occurs when receiving. I want to handle multiple writes to send and receive.

Is this possible?

About how server receives data, event handlers are possible?

If you want to write call-back oriented server code, you may find MSDN's Asynchronous Server Socket Example exactly what you're looking for.

... the sending can break if I send more data. All data got joined and errors occurs when receiving.

That is the nature of TCP . The standardized Internet protocols fall into a few categories:

             block oriented    stream oriented
reliable          SCTP              TCP
unreliable         UDP              ---

If you really want to send blocks of data, you can use SCTP, but be aware that many firewalls DROP SCTP packets because they aren't "usual". I don't know if you can reliably route SCTP packets across the open Internet.

You can wrap your own content into blocks of data with your own headers or add other "synchronization" mechanisms to your system. Consider an HTTP server: it must wait until it reads an entire request like:

GET /index.html HTTP/1.1␍␊
Host: www.example.com␍␊
␍␊

Until the server sees the CRLFCRLF sequence, it must keep the partially-read data in a buffer. The bytes might come in one at a time in a dozen or more packets. Or, if the client is sending multiple requests in a single stream, a dozen requests might come in a single packet.

You just have to handle 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