日期:2014-05-17  浏览次数:20823 次

为什么解析收到的字符串 显示出来的是乱码方块?
const int BufferSize = 8192; // 缓存大小,8192字节
  label1 .Text =("Server is running ... ");
  IPAddress ip = new IPAddress(new byte[] { 127 0, 0, 0});
  TcpListener listener = new TcpListener(ip, 10002);

  listener.Start(); // 开始侦听
  label2 .Text =("Start Listening ...");
  // 获取一个连接,中断方法

  TcpClient remoteClient = listener.AcceptTcpClient();
  // 打印连接到的客户端信息
  string aa =("Client Connected!{0} <-- {1}") + remoteClient.Client.LocalEndPoint + "" + remoteClient.Client.RemoteEndPoint;
  label3 .Text =aa .ToString ();
  // 获得流,并写入buffer中
  NetworkStream streamToClient = remoteClient.GetStream();
  byte[] buffer = new byte[BufferSize];
  int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
  label4 .Text =("Reading data, {0} bytes ...")+bytesRead;

  // 获得请求的字符串
  string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
  label5 .Text =("Received: {0}")+ msg;


最后一个label5 应该显示的是客户端发送过来的字符串,,但是显示的确实两个方块。

------解决方案--------------------
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);


用UTF8编解码
------解决方案--------------------
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);

主要看对方是用什么编码格式发送的 你就用什么编码格式接收