我在这个领域非常缺乏,我需要从服务器接收一个它不是我的字符串,这是协议:
所有发往Scratch的邮件必须以以下格式发送到端口42001:
在零字节之后是要传递的字符串消息的长度,以32位大端数字(4字节)给出。 最后,有字符串消息,其长度是消息大小的长度。 像这样:
[size] [size] [size] [size] [string message(size bytes long)]
我的程序能够连接并接收数据,但我无法将其转换为字符串。
public class SynchronousSocketClient {
public static void StartClient(IPAddress IP) {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
IPEndPoint remoteEP = new IPEndPoint(IP, 42001);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Bytes Recibidos : {0}", bytesRec);
//HERE IS THE PROBLEM...
Console.WriteLine("Echoed test = "+
System.Text.Encoding.BigEndianUnicode.GetString(bytes, 0, bytesRec));
/* // Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("broadcast \"YES\"");
// Send the data through the socket.
int bytesSent = sender.Send(msg);*/
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}}
答案 0 :(得分:2)
首先,阅读长度:
byte[] buffer = ...
ReadExactly(stream, buffer, 0, 4);
void ReadExactly(Stream stream, byte[] data, int offset, int count)
{
int read;
while(count > 0 && (read = stream.Read(data, offset, count)) > 0)
{
offset += read;
count -= read;
}
if(count != 0) throw new EndOfStreamException();
}
现在解析那个big-endian sytle:
int len = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3];
现在阅读有效载荷;例如:
ReadExactly(stream, buffer, 0, len);
获取字符串,您需要知道编码;我在这里假设UTF-8:
string s = Encoding.UTF8.GetString(buffer, 0, len);