服务器端
主要代码
csharp
//服务器socket
private Socket serverSocket;
private void InitServerSocket()
{
//创建终结点(EndPoint)
IPAddress ip = IPAddress.Any;
IPEndPoint ipe = new IPEndPoint(ip, 10030);
//创建 socket 并开始监听
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(ipe);
//开始监听
serverSocket.Listen(10);
//接受连接线程
Task.Run(() =>
{
AcceptThread(serverSocket);
});
}
private void AcceptThread(Socket serverSocket)
{
while (true)
{
try
{
//接受到client连接,为此连接建立新的socket,并接受信息
Socket tempSock = serverSocket.Accept();//为新建连接创建新的socket
//用线程来处理通信
Task.Run(() =>
{
//处理Accept后通信
HandleAccept(tempSock);
});
}
catch (Exception err)
{
}
}
}
/// <summary>
/// 处理Socket服务器接收连接线程函数
/// </summary>
/// <param name="sock">服务器连接socket</param>
private void HandleAccept(Socket sock)
{
while (true)
{
try
{
//如果连接断开,则退出线程
//if (!sock.Connected)
//{
// sock.Close();
// break;
//}
if (sock.Poll(-1, SelectMode.SelectRead))
{
//接收
byte[] buffer = new byte[4096];
int num = sock.Receive(buffer);
if (num == 0)
{
//连接断开了
sock.Close();
break;
}
//瘵缓冲区字节转换为字符串
string sCmd = Encoding.UTF8.GetString(buffer, 0, num);
//如果是空字符串,不处理
if (sCmd.Trim() == "") continue;
//命令包
var cmd = JsonConvert.DeserializeObject<CmdPackage>(sCmd);
//处理命令
HandleCmd(sock, cmd);
}
}
catch (Exception err)
{
}
}
}
/// <summary>
/// 处理命令
/// </summary>
/// <param name="sock">服务器socket</param>
/// <param name="cmd">命令包</param>
private void HandleCmd(Socket sock, CmdPackage cmd)
{
if (cmd.Cmd == "Start")
{
//启动
string ip = cmd.Parameters["ip"];
info("Start,ip:" + ip);
int ret = NrClientSDK.NrClientSDK_NewReader(ip);
//开始标志
startFlag = true;
//返回包
CmdPackage retCmd = new CmdPackage();
retCmd.Cmd = "Return";
retCmd.Parameters.Add("ret", ret.ToString());
//发送
var sRet = JsonConvert.SerializeObject(retCmd);
byte[] ba = Encoding.UTF8.GetBytes(sRet);
sock.Send(ba);
}
}
CmdPackage 类
csharp
class CmdPackage
{
public string Cmd { get; set; }
public Dictionary<string, string> Parameters { get; set; }= new Dictionary<string, string>();
}
客户端
csharp
/// <summary>
/// 发送命令
/// </summary>
/// <param name="cmd">命令包对象</param>
/// <returns>接收到返回的字符串</returns>
private string SendCmd(CmdPackage cmd)
{
IPAddress iP = IPAddress.Parse(serverIP);
IPEndPoint iPEndPoint = new IPEndPoint(iP, serverPort);
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建与远程主机的连接
clientSocket.Connect(iPEndPoint);
//发送命令
var sCmd = JsonConvert.SerializeObject(cmd);
byte[] buffer = Encoding.UTF8.GetBytes(sCmd);
clientSocket.Send(buffer);
//接收返回
byte[] bufRcv = new byte[4096];
int num = clientSocket.Receive(bufRcv);
//返回传为字符串
string sRcv = Encoding.UTF8.GetString(bufRcv, 0, num);
//关闭连接
clientSocket.Close();
//返回
return sRcv;
}