这是我的客户端从服务器接收数据的代码,该服务器是模拟器。在调试代码时,我在此数组中收到了空值,称为receivedBytes
:
// define buffer
byte[] receivedBytes = new byte[2048];
// define endpoint
IPHostEntry ipHost = Dns.Resolve("192.168.1.55");
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1001);
// connect
Console.WriteLine("Starting: Creating Socket object");
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Successfully connected to {0}", sender.RemoteEndPoint);
// get user input
Console.WriteLine("Enter Client Message :");
string sendingMessage = Console.ReadLine();
// send
Console.WriteLine("Creating message:{0}", sendingMessage);
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
sender.Send(forwardMessage);
// receive
int totalBytesReceived = sender.Receive(receivedBytes);
Console.WriteLine("Message provided from server: {0}", Encoding.Unicode.GetString(receivedBytes, 0, totalBytesReceived));
// close
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadLine();
我在这里做错了什么?
答案 0 :(得分:0)
实际上转换代码是错误的。
string sendingMessage = "Hello, World";
byte[] forwardMessage = Encoding.Default.GetBytes(sendingMessage);
string receivedMessage = Encoding.Unicode.GetString(forwardMessage, 0,forwardMessage.Length);
之后,收到的消息将被打破。
它做什么?它获取GetBytes的默认编码,而不是使用UTF-16编码来获取字符串。你应该使用Encoding.Default.GetBytes和Encoding.Default.GetString。