java Socket与C#通信中中文乱码问题的解决方案
作者:网络转载 发布时间:[ 2012/12/13 9:53:40 ] 推荐标签:
ServerListen类
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System;
namespace TCPServer
{
public class ServerListen
{
public static void Run(Object iGetClientData)
{
IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("IP地址"), 端口);//本机预使用的IP和端口
Socket skServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
skServer.Bind(serverIP);
skServer.Listen(100);//连接客户端的上限
while (true)
{
Socket skClient;
try
{
//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
skClient = skServer.Accept();
}
catch (Exception ex)
{
LogHelper.Err("接收用户连接失败 ServerListen.Run Socket.Accept", ex);
continue;
}
ThrClient thrC = new ThrClient(skServer, skClient, (IGetClientData)iGetClientData);
Thread t = new Thread(thrC.Run);
t.Start();
}
}
}
}
ThrClient类
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;
}
}
}
}
上面是主要的代码,还有一个向外界提供的接口,这里不贴出来了。
两种语言之间的通信问题真的是挺令人头疼的,我们这也是通过猜测然后多次实验才找到了答案。所以,像《大话设计模式》中提到的,不痴迷,不成功。
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11