C#Socket传送/接收中文出现乱码的解决办法

来源:互联网 发布:c语言西北工业大学 编辑:程序博客网 时间:2024/06/09 22:56

我的程式采用Base64编码方式

1.Client

try
   {
    TcpClient client = new TcpClient();
    Console.WriteLine("Connecting.....");
   
    client.Connect("172.18.33.85",8001);
   
    Console.WriteLine("Connected");
    Console.Write("Enter the string to be transmitted : ");
   
    string str = Console.ReadLine();
    Stream stream = client.GetStream();

    //转换发送字串为Base64编码
    byte[] bytes1 = Encoding.GetEncoding("BIG5").GetBytes(str);
    string encode = Convert.ToBase64String(bytes1);

    ASCIIEncoding ascii = new ASCIIEncoding();
    byte[] bytes2 = ascii.GetBytes(encode);
    Console.WriteLine("Transmitting......");

    stream.Write(bytes2,0,bytes2.Length);
    byte[] bytes = new byte[100];
    int j = stream.Read(bytes,0,100);
    
    for (int i=0;i<j;i++)
    {
     Console.Write(Convert.ToChar(bytes[i]));
    }
    client.Close();
   }
   catch(Exception e)
   {
    Console.WriteLine("Error..... " + e.StackTrace);
   }
   Console.ReadLine();

2.Server

try
   {
    IPAddress ip = IPAddress.Parse("172.18.33.85");//这里是你的ip
    TcpListener myListener = new TcpListener(ip,8001);

    myListener.Start();

    Console.WriteLine("Server is running at port 8001..."); 
    Console.WriteLine("The local End point is  :" + myListener.LocalEndpoint);
    Console.WriteLine("Waiting for a connection.....");

    Socket mySocket = myListener.AcceptSocket();
    Console.WriteLine("Connection accepted from " + mySocket.RemoteEndPoint);

    byte[] bytes1 = new byte[100];
    int j = mySocket.Receive(bytes1);
    Console.WriteLine("Recieved...");
    string encode = "" ;
    for (int i=0;i<j;i++)
    {
     encode += Convert.ToChar(bytes1[i]);
    }

    //还原Base64编码的接收字串
    byte[] bytes2 = Convert.FromBase64String(encode);
    string decode = Encoding.GetEncoding("BIG5").GetString(bytes2);
    Console.WriteLine(decode);

   
    ASCIIEncoding ascii = new ASCIIEncoding();
    mySocket.Send(ascii.GetBytes("The string was recieved by the server."));
    Console.Write("Sent Acknowledgement");
    
    mySocket.Close();
    myListener.Stop();
    Console.ReadLine();
   }
   catch(Exception e)
   {
    Console.WriteLine("Error..... " + e.StackTrace);
   }