C # reads binary data from a socket

I am working on an application that reads and writes binary data from and to a socket. Therefore, I first create a socket with TcpClient. But I am stuck on reading data from a socket. Are there any code examples for reading binary data from a socket?

Specifically, there are two things that I do not understand. First, how do you know if a message has been received? Do I need to create some kind of loop for this? And second: what is the best way to read this data, since the data I receive is binary, and not just a regular string.

thank

+3
source share
4 answers

TCPClient Microsoft .

TCPClient

Microsoft :

// Get the stream
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[256];

// String to store the response ASCII representation.
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
int bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);

GetStream TCPClient ( 256 ) .

, , . , 100% , , .

...

, ?

, , , , ( , ).

, , - ( ) (, ) .

, :

DATA | END

, , , . DATA , .

?

/ , . ( ), ASCII Encoding GetString GetBytes.

( ) , TCP. , , , .

, .

+5

MSDN. , TcpClients ( , ) TcpListeners ( ), ( / ).

+1

, , . , , . . NetworkStream, NetworkStream stream = client.GetStream();. , int .

public void send(NetworkStream stream, byte[] buf) {
    stream.Write(BitConverter.GetBytes(buf.Length), 0, 4);
    stream.Write(buf, 0, buf.Length);
}

public byte[] receive(NetworkStream stream) {
    byte[] lengthBytes = new byte[4];
    int read = stream.Read(lengthBytes, 0, 4);
    // read contains the number of read bytes, so we can check it if we want
    int length = BitConverter.GetInt32(lengthBytes);
    byte[] buf = new byte[length];
    stream.Read(buf, 0, buf.length);
    return buf;
}
0

GetStream TcpClient, NetworkStream, . BinaryReader BinaryWriter .NET(, Int32s, Strings et cetera) NetworkStream . NetworkStream.Read, NetworkStream.BeginRead NetworkStream.DataAvailable; . http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream_members.aspx .

0

Source: https://habr.com/ru/post/1764522/


All Articles