网上流传的一种方法是修改web.config文件,将utf-8修改为gb2312:
<system.web>
......
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" fileEncoding="gb2312" />
......
</system.web>
但经测试这种方法并没有用,其实这不仅仅是在WebService中遇到的问题,C#的socket在与其他进程传输中文时都可能会出现中文变乱码的问题,一般是编码的问题引起的,解决方法如下:
Encoding myEncoding=Encoding.GetEncoding("GB2312");
Byte[] ReceiveBytes=new Byte[1024];
int i=saccept.Receive(ReceiveBytes,ReceiveBytes.Length,0);
ReceiveMessage.Text=myEncoding.GetString(ReceiveBytes);
Byte[] byteDateTime=myEncoding.GetBytes(datetime.ToCharArray());
Byte[] SendBytes=myEncoding.GetBytes(SendMessage.Text.ToCharArray());
贴出我的代码:
public string Sendtest(string sendStr)
{
Encoding myEncoding=Encoding.GetEncoding("GB2312");
IPAddress myIP = IPAddress.Parse("192.168.1.105");
IPEndPoint ipe = new IPEndPoint(myIP,12000);
string result = "";
string recvStr = "";
string end1 = "\0";
string end2 = "\n";
//byte[] bs = Encoding.ASCII.GetBytes(sendStr);
byte[] bs = myEncoding.GetBytes(sendStr);
byte[] recvBytes = new byte[1024];
byte[] recvData = new byte[1024];
try
{
Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
s.Connect(ipe);
s.Send(bs,0,bs.Length,SocketFlags.None); //
//Thread.Sleep(200);
s.Receive(recvData,0,recvData.Length,SocketFlags.None);
//Thread.Sleep(1000);
//recvStr = Encoding.ASCII.GetString(recvData,0,recvData.Length);
recvStr = myEncoding.GetString(recvData);
string covStr = recvStr.TrimEnd(end1.ToCharArray());
string covStr2 = covStr.TrimEnd(end2.ToCharArray());
result = covStr2;
s.Close();
}
catch(Exception Err)
{
result = "Socket Error"+"\n"+Err;
//s.Close();
}
return result;
}