java Socket与C#通信中中文乱码问题的解决方案
最近正在做一个项目,其中遇到了一个问题就是java与.NET之间的通信问题。具体的问题是这样的:
客户端使用java,服务器端使用的是C#。两者之间使用基于TCP的Socket通信方式。可是,做了一个测试小例子,结果从客户端传过来的都是乱码。于是上网查,希望可以找到解决方法,可是,网上有好多的答案,经过了很多的实验,都不能很好的解决。没办法只能靠自己一点一点的排查了。
经过一番努力,最终找到了原因:C#和java的编码方式不同。虽然找到了原因,但是网上关于这个问题的答案也是百家争鸣,在这里就给出源代码,希望对大家有帮助。
首先是客户端的java代码(这是比较简单的部分)
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.Net.Sockets;using System.Threading;namespace TCPServer{ public class ThrClient { private static readonly StringBuilder sb = new StringBuilder(); private Socket skServer; private Socket skClient; private IPEndPoint clientIP; private IGetClientData iGetClientData; //每次接收发送的临时信息 private byte[] sendData;//发送的信息 private byte[] receiveData = new byte[1024];//接收信息 private int receiveN; private int netID; /// <summary> /// ThrClient构造方法 /// </summary> /// <param name="pSkServer">服务端</param> /// <param name="pSkClient">客户端</param> public ThrClient(Socket pSkServer, Socket pSkClient,IGetClientData iGetClientData) { this.skServer = pSkServer; this.skClient = pSkClient; this.iGetClientData = iGetClientData; this.clientIP = (IPEndPoint)this.skClient.RemoteEndPoint; //下面一定要使用UTF8而不能使用Uncode this.sendData = Encoding.UTF8.GetBytes("success"); try { this.skClient.Send(sendData, sendData.Length, SocketFlags.None);//发送信息 } catch (Exception ex) { LogHelper.Err("发送第一次连接成功信息 ThrClient.ThrClient Socket.Send", ex); } } public void Run() { while (true) { try { this.receiveN = skClient.Receive(this.receiveData);//接收 if (this.receiveN != 0) { string removeMsg = Encoding.UTF8 .GetString(receiveData, 0, receiveN); iGetClientData.getThread(removeMsg); } } catch (Exception ex) { iGetClientData.getClientIP(((IPEndPoint)skClient.RemoteEndPoint).Address); break; } } } }上面是主要的代码,还有一个向外界提供的接口,这里就不贴出来了。
两种语言之间的通信问题真的是挺令人头疼的,我们这也是通过猜测然后多次实验才找到了答案。所以,就像《大话设计模式》中提到的,不痴迷,不成功。