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

我的程式采用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);
   }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值