Asynchronous sockets, explain the logic.
-
Here's an example.
ReceiveCallback
from MSDN.int bytesRecv = clientSocket.EndReceive(result);
if (bytesRecv > 0)
{
clientSocket.BeginReceive(ci.Buffer, 0, ci.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ci);
}
else
{
Console.WriteLine("Response");
}
Let's say the size of the buffer on the client's side of 16 byte. If I send 32 bayts from the server, callback only works twice by 16 + 16 bay. In this regard, verification is not operational
bytesRecv = 0
andConsole.WriteLine("")
It doesn't work because the third callback is not launched. What am I doing wrong?
-
An example of MSDN implies that the other side will close the flow after the data are sent:
socket.Shutdown(SocketShutdown.Send);
In this case, the consignee will read a zero byte at reading.
Such a regime of work - sending data, closing up the flow, accepting data - is the simplest for the TCP protocol and the historical first used. Therefore, most of the examples of work with the sockets are written under such a protocol.
If you need to keep the connection to the established, you need to come up with a way to define the boundaries of the message. This may be either a special marker of the end of the message or a clear transfer of the length before the message itself.
For example, the HTTP protocol uses a combined approach - the head restraint block ends with two row translations and the data block (as referred to in the HTTP Protocol) body of contents) has a length exactly
Content-Length
Byte. If the titleContent-Length
not specified - the datablock ends with sealing.