为什么下面的代码只能实现英文聊天,如果使用中文则出现乱码?请问大家如何解决?
public class Chat
{
private static IPAddress remoteIPAddress = IPAddress.Parse("127.0.0.1");
private static int remotePort;
private static int localPort; [STAThread]
static void Main(string[] args)
{
Console.WriteLine("请输入本机端口");
localPort = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("请输入远程端口");
remotePort = Convert.ToInt16(Console.ReadLine());
Thread thread = new Thread(new ThreadStart(Receiver));
thread.Start();
while(true)
{
Send(Console.ReadLine());
}
}
private static void Send(string datagram)
{
UdpClient sender = new UdpClient();
IPEndPoint ipEndPoint = new IPEndPoint(remoteIPAddress,remotePort);
byte[] bytes = Encoding.ASCII.GetBytes(datagram);
sender.Send(bytes,bytes.Length,ipEndPoint);
sender.Close();
}
private static void Receiver()
{
UdpClient receivingUdpClient = new UdpClient(localPort);
IPEndPoint RemoteIPEndPoint = null;
Console.WriteLine("------------------Ready for chat!!!!!----------------------");
while(true)
{
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIPEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
Console.WriteLine("-" + returnData);
}
}

}

解决方案 »

  1.   

    using System;
    using System.Text;namespace ConvertExample
    {
       class ConvertExampleClass
       {
          static void Main()
          {
             string unicodeString = "This string contains the unicode character Pi(\u03a0)";         // Create two different encodings.
             Encoding ascii = Encoding.ASCII;
             Encoding unicode = Encoding.Unicode;         // Convert the string into a byte[].
             byte[] unicodeBytes = unicode.GetBytes(unicodeString);         // Perform the conversion from one encoding to the other.
             byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);
                
             // Convert the new byte[] into a char[] and then into a string.
             // This is a slightly different approach to converting to illustrate
             // the use of GetCharCount/GetChars.
             char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
             ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
             string asciiString = new string(asciiChars);         // Display the strings created before and after the conversion.
             Console.WriteLine("Original string: {0}", unicodeString);
             Console.WriteLine("Ascii converted string: {0}", asciiString);
          }
       }
    }
      

  2.   

    出现乱码一般都编码出现问题了
    byte[] bytes = Encoding.BigEndianUnicode.GetBytes(datagram);
      

  3.   

    楼上的朋友我这样byte[] bytes = Encoding.BigEndianUnicode.GetBytes(datagram);在接收端还是不能正确显示中文呀?大家帮帮我呀!