添加项目文件。
This commit is contained in:
@@ -0,0 +1,943 @@
|
||||
//using JinYuan.VirtualDataLibrary.Utlis;
|
||||
//using System;
|
||||
//using System.Collections.Generic;
|
||||
//using System.IO;
|
||||
//using System.Linq;
|
||||
//using System.Text;
|
||||
using JinYuan.MES.Models;
|
||||
using Newtonsoft.Json;
|
||||
using PLCCommunication.BasicFramework;
|
||||
|
||||
//using System.Net;
|
||||
//using System.Net.Sockets;
|
||||
//using System.Threading.Tasks;
|
||||
|
||||
|
||||
//namespace JinYuan.VirtualDataLibrary.Utlis
|
||||
//{
|
||||
// public class PrintDataModel
|
||||
// {
|
||||
// public string PrintTaskId { get; set; } = Guid.NewGuid().ToString();
|
||||
// public string PrinterName { get; set; }
|
||||
// public string Code { get; set; }
|
||||
// public Dictionary<string, string> PrintFields { get; set; } = new Dictionary<string, string>();
|
||||
// public int CopyCount { get; set; } = 1;
|
||||
// public DateTime PrintTime { get; set; } = DateTime.Now;
|
||||
// }
|
||||
|
||||
// // 通信响应实体(服务端返回处理结果)
|
||||
// public class PrintResponseModel
|
||||
// {
|
||||
// public bool Success { get; set; }
|
||||
// public string Message { get; set; }
|
||||
// public string PrintTaskId { get; set; }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// Socket通信工具类(兼容所有.NET版本)
|
||||
// /// </summary>
|
||||
// public static class SocketPrintHelper
|
||||
// {
|
||||
// // JSON序列化配置(中文不转义、缩进)
|
||||
// private static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
|
||||
// {
|
||||
// Formatting = Formatting.Indented,
|
||||
// StringEscapeHandling = StringEscapeHandling.EscapeNonAscii // 中文不转义
|
||||
// };
|
||||
|
||||
// /// <summary>
|
||||
// /// 发送打印数据(客户端核心方法)
|
||||
// /// </summary>
|
||||
// public static PrintResponseModel SendPrintData(string serverIp, int serverPort, Dictionary<string, string> printData, int timeout = 5000)
|
||||
// {
|
||||
// TcpClient tcpClient = null;
|
||||
// NetworkStream stream = null;
|
||||
// try
|
||||
// {
|
||||
// tcpClient = new TcpClient
|
||||
// {
|
||||
// ReceiveTimeout = timeout,
|
||||
// SendTimeout = timeout
|
||||
// };
|
||||
// tcpClient.Connect(serverIp, serverPort);
|
||||
// stream = tcpClient.GetStream();
|
||||
// bool bconnnet = tcpClient.Connected;
|
||||
|
||||
|
||||
// // 使用Newtonsoft.Json序列化
|
||||
// string jsonData = JsonConvert.SerializeObject(printData, _jsonSettings);
|
||||
// byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);
|
||||
|
||||
// // 发送数据长度
|
||||
// byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length);
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBytes);
|
||||
// stream.Write(lengthBytes, 0, lengthBytes.Length);
|
||||
// stream.Write(jsonBytes, 0, jsonBytes.Length);
|
||||
// Console.WriteLine($"已发送打印数据(任务ID:{printData}):\n{jsonData}");
|
||||
|
||||
// // 接收响应
|
||||
// PrintResponseModel response = ReceivePrintResponse(stream, printData["container"], timeout);
|
||||
// return response;
|
||||
// }
|
||||
// catch (SocketException ex)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"连接服务端失败:{ex.Message}(IP:{serverIp}:{serverPort})",
|
||||
// PrintTaskId = printData["container"]
|
||||
// };
|
||||
// }
|
||||
// catch (TimeoutException)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"通信超时(超时时间:{timeout}ms)",
|
||||
// PrintTaskId = printData["container"]
|
||||
// };
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"发送打印数据失败:{ex.Message}",
|
||||
// PrintTaskId = printData["container"]
|
||||
// };
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// stream?.Close();
|
||||
// tcpClient?.Close();
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 接收服务端响应
|
||||
// /// </summary>
|
||||
// private static PrintResponseModel ReceivePrintResponse(NetworkStream stream, string printTaskId, int timeout)
|
||||
// {
|
||||
// // 读取长度
|
||||
// byte[] lengthBuffer = new byte[4];
|
||||
// int readLength = stream.Read(lengthBuffer, 0, lengthBuffer.Length);
|
||||
// if (readLength != 4)
|
||||
// throw new Exception("读取响应长度失败");
|
||||
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBuffer);
|
||||
// int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
|
||||
|
||||
// // 读取数据
|
||||
// byte[] dataBuffer = new byte[dataLength];
|
||||
// int totalRead = 0;
|
||||
// while (totalRead < dataLength)
|
||||
// {
|
||||
// int read = stream.Read(dataBuffer, totalRead, dataLength - totalRead);
|
||||
// if (read == 0)
|
||||
// throw new Exception("服务端断开连接");
|
||||
// totalRead += read;
|
||||
// }
|
||||
|
||||
// // 使用Newtonsoft.Json反序列化
|
||||
// string jsonResponse = Encoding.UTF8.GetString(dataBuffer);
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = true,
|
||||
// Message = $"发送打印数据成功",
|
||||
// PrintTaskId = printTaskId
|
||||
// };
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 服务端接收打印数据
|
||||
// /// </summary>
|
||||
// public static PrintDataModel ReceivePrintData(NetworkStream stream, int timeout)
|
||||
// {
|
||||
// // 读取长度
|
||||
// byte[] lengthBuffer = new byte[4];
|
||||
// int readLength = stream.Read(lengthBuffer, 0, lengthBuffer.Length);
|
||||
// if (readLength != 4)
|
||||
// throw new Exception("读取数据长度失败");
|
||||
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBuffer);
|
||||
// int dataLength = BitConverter.ToInt32(lengthBuffer, 0);
|
||||
|
||||
// // 读取数据
|
||||
// byte[] dataBuffer = new byte[dataLength];
|
||||
// int totalRead = 0;
|
||||
// while (totalRead < dataLength)
|
||||
// {
|
||||
// int read = stream.Read(dataBuffer, totalRead, dataLength - totalRead);
|
||||
// if (read == 0)
|
||||
// throw new Exception("客户端断开连接");
|
||||
// totalRead += read;
|
||||
// }
|
||||
|
||||
// // 核心修改:Newtonsoft.Json反序列化
|
||||
// string jsonData = Encoding.UTF8.GetString(dataBuffer);
|
||||
// PrintDataModel printData = JsonConvert.DeserializeObject<PrintDataModel>(jsonData, _jsonSettings);
|
||||
// Console.WriteLine($"服务端接收打印数据(任务ID:{printData.PrintTaskId}):\n{jsonData}");
|
||||
// return printData;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 服务端发送响应数据
|
||||
// /// </summary>
|
||||
// public static void SendPrintResponse(NetworkStream stream, PrintResponseModel response)
|
||||
// {
|
||||
// // 核心修改:Newtonsoft.Json序列化
|
||||
// string jsonResponse = JsonConvert.SerializeObject(response, _jsonSettings);
|
||||
// byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonResponse);
|
||||
|
||||
// // 发送长度+数据(逻辑不变)
|
||||
// byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length);
|
||||
// if (BitConverter.IsLittleEndian)
|
||||
// Array.Reverse(lengthBytes);
|
||||
// stream.Write(lengthBytes, 0, lengthBytes.Length);
|
||||
// stream.Write(jsonBytes, 0, jsonBytes.Length);
|
||||
// }
|
||||
// }
|
||||
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 打印数据发送客户端
|
||||
///// </summary>
|
||||
//public class PrintDataClient
|
||||
//{
|
||||
// private readonly string _serverIp;
|
||||
// private readonly int _serverPort;
|
||||
|
||||
// public PrintDataClient(string serverIp, int serverPort)
|
||||
// {
|
||||
// _serverIp = serverIp;
|
||||
// _serverPort = serverPort;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 构建并发送打印数据
|
||||
// /// </summary>
|
||||
// public void SendPrintTask(Dictionary<string, string> printData)
|
||||
// {
|
||||
|
||||
// // 发送打印数据
|
||||
// PrintResponseModel response = SocketPrintHelper.SendPrintData(_serverIp, _serverPort, printData, 5000);
|
||||
|
||||
// // 处理响应结果
|
||||
// if (response.Success)
|
||||
// {
|
||||
// Console.WriteLine($"打印任务提交成功(任务ID:{response.PrintTaskId}):{response.Message}");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Console.WriteLine($"打印任务提交失败(任务ID:{response.PrintTaskId}):{response.Message}");
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
|
||||
///// <summary>
|
||||
///// 打印数据接收服务端(打印机终端/打印服务器侧)
|
||||
///// </summary>
|
||||
//public class PrintDataServer
|
||||
//{
|
||||
// private readonly int _port;
|
||||
// private TcpListener _listener;
|
||||
// private bool _isRunning;
|
||||
|
||||
// public PrintDataServer(int port)
|
||||
// {
|
||||
// _port = port;
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 启动服务端
|
||||
// /// </summary>
|
||||
// public void Start()
|
||||
// {
|
||||
// _isRunning = true;
|
||||
// _listener = new TcpListener(IPAddress.Any, _port);
|
||||
// _listener.Start();
|
||||
// Console.WriteLine($"打印数据服务端已启动,监听端口:{_port}");
|
||||
|
||||
// // 异步接受客户端连接
|
||||
// Task.Run(async () =>
|
||||
// {
|
||||
// while (_isRunning)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// TcpClient client = await _listener.AcceptTcpClientAsync();
|
||||
// Console.WriteLine($"客户端连接:{((IPEndPoint)client.Client.RemoteEndPoint).Address}");
|
||||
// // 处理客户端请求(异步,避免阻塞)
|
||||
// HandleClientAsync(client);
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// if (_isRunning)
|
||||
// Console.WriteLine($"接受客户端连接失败:{ex.Message}");
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 处理客户端请求
|
||||
// /// </summary>
|
||||
// private async Task HandleClientAsync(TcpClient client)
|
||||
// {
|
||||
// using (client)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// NetworkStream stream = client.GetStream();
|
||||
// client.ReceiveTimeout = 5000;
|
||||
// client.SendTimeout = 5000;
|
||||
|
||||
// // 1. 接收打印数据
|
||||
// PrintDataModel printData = SocketPrintHelper.ReceivePrintData(stream, 5000);
|
||||
|
||||
// // 2. 处理打印任务(对接你的打印逻辑)
|
||||
// PrintResponseModel response = ProcessPrintTask(printData);
|
||||
|
||||
// // 3. 发送响应给客户端
|
||||
// SocketPrintHelper.SendPrintResponse(stream, response);
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// Console.WriteLine($"处理客户端请求失败:{ex.Message}");
|
||||
// // 发送失败响应
|
||||
// try
|
||||
// {
|
||||
// SocketPrintHelper.SendPrintResponse(client.GetStream(), new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = ex.Message,
|
||||
// PrintTaskId = ""
|
||||
// });
|
||||
// }
|
||||
// catch { }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 处理打印任务
|
||||
// /// </summary>
|
||||
// private PrintResponseModel ProcessPrintTask(PrintDataModel printData)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// // --------------------------
|
||||
// // 此处对接你的实际打印逻辑:
|
||||
// // 1. 根据PrinterName选择打印机
|
||||
// // 2. 解析PrintFields填充打印模板
|
||||
// // 3. 调用打印机SDK执行打印
|
||||
// // --------------------------
|
||||
// Console.WriteLine($"开始处理打印任务(ID:{printData.PrintTaskId}):");
|
||||
// Console.WriteLine($" 打印机:{printData.PrinterName}");
|
||||
// Console.WriteLine($" 托盘号:{printData.Code}");
|
||||
// Console.WriteLine($" 打印份数:{printData.CopyCount}");
|
||||
// Console.WriteLine($" 打印字段:");
|
||||
// foreach (var field in printData.PrintFields)
|
||||
// {
|
||||
// Console.WriteLine($" {field.Key} = {field.Value}");
|
||||
// }
|
||||
|
||||
// // 模拟打印成功(替换为你的实际打印代码)
|
||||
// // CommonMethods.PrintLabel(printData);
|
||||
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = true,
|
||||
// Message = $"打印任务已执行(份数:{printData.CopyCount})",
|
||||
// PrintTaskId = printData.PrintTaskId
|
||||
// };
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// return new PrintResponseModel
|
||||
// {
|
||||
// Success = false,
|
||||
// Message = $"打印任务执行失败:{ex.Message}",
|
||||
// PrintTaskId = printData.PrintTaskId
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 停止服务端
|
||||
// /// </summary>
|
||||
// public void Stop()
|
||||
// {
|
||||
// _isRunning = false;
|
||||
// _listener?.Stop();
|
||||
// Console.WriteLine("打印数据服务端已停止");
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PrintSocket
|
||||
{
|
||||
public class StateObject
|
||||
{
|
||||
public Socket workSocket = null;
|
||||
public const int BufferSize = 2000;
|
||||
public byte[] buffer = new byte[BufferSize];
|
||||
public StringBuilder sb = new StringBuilder();
|
||||
}
|
||||
|
||||
//服务端类
|
||||
public class TCPServer
|
||||
{
|
||||
//私有变量
|
||||
private SocketMessage m_SocketMsgDelegate = null;
|
||||
private Socket m_Listener = null;
|
||||
private Socket m_ServerHandler = null;
|
||||
|
||||
//公开变量
|
||||
public delegate void SocketMessage(object obj);
|
||||
public string m_strInfo = null;
|
||||
|
||||
public void InitServer(string strAddr, int nPort, SocketMessage sockMsg = null) //初始化
|
||||
{
|
||||
if (sockMsg != null)
|
||||
{
|
||||
m_SocketMsgDelegate = sockMsg;
|
||||
}
|
||||
if (m_Listener != null)
|
||||
{
|
||||
try { m_Listener.Close(); } catch { }
|
||||
m_Listener = null;
|
||||
}
|
||||
|
||||
//创建套接字
|
||||
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(strAddr), nPort);
|
||||
m_Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
try
|
||||
{
|
||||
m_Listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
|
||||
m_Listener.Bind(ipe);
|
||||
m_Listener.Listen(10);
|
||||
|
||||
//开启异步监听连接
|
||||
m_Listener.BeginAccept(new AsyncCallback(AcceptCallback), m_Listener);
|
||||
m_SocketMsgDelegate?.Invoke("Server online");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e.Message);
|
||||
m_SocketMsgDelegate?.Invoke(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private void AcceptCallback(IAsyncResult iar)
|
||||
{
|
||||
Socket listener = (Socket)iar.AsyncState;
|
||||
m_ServerHandler = listener.EndAccept(iar); //结束接收请求
|
||||
|
||||
//创建状态对象
|
||||
StateObject state = new StateObject();
|
||||
state.workSocket = m_ServerHandler;
|
||||
m_strInfo = m_ServerHandler.RemoteEndPoint.ToString();
|
||||
m_SocketMsgDelegate?.Invoke("Client online");
|
||||
|
||||
//开启数据回调
|
||||
m_ServerHandler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
|
||||
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
|
||||
}
|
||||
|
||||
private void ReceiveCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
StateObject state = (StateObject)ar.AsyncState;
|
||||
Socket handler = state.workSocket;
|
||||
|
||||
if (handler != null && handler.Connected)
|
||||
{
|
||||
//读取数据
|
||||
int bytesRead = handler.EndReceive(ar);
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
string content = Encoding.UTF8.GetString(state.buffer, 0, bytesRead);
|
||||
state.sb.Append(content);
|
||||
string fullContent = state.sb.ToString();
|
||||
|
||||
m_SocketMsgDelegate?.Invoke(fullContent);
|
||||
|
||||
state.sb.Clear();
|
||||
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Client offline");
|
||||
m_Listener.BeginAccept(new AsyncCallback(AcceptCallback), m_Listener);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Server offline");
|
||||
}
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
m_SocketMsgDelegate?.Invoke($"{ex.ErrorCode} {ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke("Client offline");
|
||||
m_Listener.BeginAccept(new AsyncCallback(AcceptCallback), m_Listener);
|
||||
}
|
||||
}
|
||||
|
||||
public void Send(String data)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_ServerHandler == null || !m_ServerHandler.Connected)
|
||||
{
|
||||
Console.WriteLine("服务器Socket未连接,无法发送数据");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] byteData = Encoding.UTF8.GetBytes(data);
|
||||
m_ServerHandler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), m_ServerHandler);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"服务器发送数据异常:{ex.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
Socket handler = (Socket)ar.AsyncState;
|
||||
int bytesSent = handler.EndSend(ar);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"服务器发送回调异常:{e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void CloseSocket()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_ServerHandler != null && m_ServerHandler.Connected)
|
||||
{
|
||||
m_ServerHandler.Shutdown(SocketShutdown.Both);
|
||||
m_ServerHandler.Close();
|
||||
}
|
||||
m_Listener?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"关闭服务器Socket异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//客户端类
|
||||
public class TCPClient
|
||||
{
|
||||
public delegate void SocketMessage(object obj);
|
||||
private SocketMessage m_SocketMsgDelegate = null;
|
||||
private Socket m_Client = null;
|
||||
private Socket m_Handler = null;
|
||||
private IPEndPoint m_ipe;
|
||||
public string m_strInfo;
|
||||
|
||||
public void InitClient(string strAddr, int nPort, SocketMessage sockMsg = null)
|
||||
{
|
||||
if (sockMsg != null)
|
||||
{
|
||||
m_SocketMsgDelegate = sockMsg;
|
||||
}
|
||||
if (m_Client != null)
|
||||
{
|
||||
try { m_Client.Close(); } catch { }
|
||||
m_Client = null;
|
||||
}
|
||||
try
|
||||
{
|
||||
//端口及IP
|
||||
m_ipe = new IPEndPoint(IPAddress.Parse(strAddr), nPort);
|
||||
//创建套接字
|
||||
m_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
|
||||
//开始连接到服务器
|
||||
m_Client.BeginConnect(m_ipe, new AsyncCallback(ConnectCallback), m_Client);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 捕获初始化异常,仅提示不抛异常
|
||||
string errorMsg = $"客户端初始化连接失败:{e.Message}";
|
||||
Console.WriteLine(errorMsg);
|
||||
m_SocketMsgDelegate?.Invoke(errorMsg);
|
||||
}
|
||||
}
|
||||
|
||||
private void ConnectCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_Handler = (Socket)ar.AsyncState;
|
||||
m_Handler.EndConnect(ar);
|
||||
|
||||
m_strInfo = m_Handler.LocalEndPoint.ToString();
|
||||
m_SocketMsgDelegate?.Invoke("Connection");
|
||||
|
||||
|
||||
//创建状态对象
|
||||
StateObject state = new StateObject();
|
||||
state.workSocket = m_Handler;
|
||||
|
||||
//开启数据回调
|
||||
m_Handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
|
||||
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"客户端连接异常:{e.Message}");
|
||||
m_SocketMsgDelegate?.Invoke($"ConnectError: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void ReceiveCallBack(IAsyncResult iar)
|
||||
{
|
||||
try
|
||||
{
|
||||
StateObject state = (StateObject)iar.AsyncState;
|
||||
Socket handler = state.workSocket;
|
||||
|
||||
if (handler != null && handler.Connected)
|
||||
{
|
||||
//读取数据
|
||||
int bytesRead = handler.EndReceive(iar);
|
||||
if (bytesRead > 0)
|
||||
{
|
||||
string content = Encoding.UTF8.GetString(state.buffer, 0, bytesRead);
|
||||
state.sb.Append(content);
|
||||
string fullContent = state.sb.ToString();
|
||||
|
||||
m_SocketMsgDelegate?.Invoke(fullContent);
|
||||
|
||||
state.sb.Clear();
|
||||
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Server offline");
|
||||
|
||||
//关闭并且允许重复使用
|
||||
m_Client.Disconnect(true);
|
||||
//重新连接到服务器
|
||||
m_Client.BeginConnect(m_ipe, new AsyncCallback(ConnectCallback), m_Client);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m_SocketMsgDelegate?.Invoke("Client offline");
|
||||
}
|
||||
|
||||
}
|
||||
catch (SocketException ex)
|
||||
{
|
||||
Console.WriteLine($"客户端接收异常:{ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke($"{ex.ErrorCode} {ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke("DISCONNECT");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Send(Dictionary<string, string> printData)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 前置校验:确保 Socket 有效且已连接
|
||||
if (m_Handler == null || !m_Handler.Connected)
|
||||
{
|
||||
Console.WriteLine("客户端Socket未连接,无法发送JSON数据");
|
||||
m_SocketMsgDelegate?.Invoke("Socket未连接,发送失败");
|
||||
|
||||
return;
|
||||
}
|
||||
// 使用Newtonsoft.Json序列化
|
||||
string jsonData = JsonConvert.SerializeObject(printData);
|
||||
byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);
|
||||
m_Handler.BeginSend(jsonBytes, 0, jsonBytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), m_Handler);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 捕获并上报所有异常
|
||||
Console.WriteLine($"客户端发送JSON数据异常:{ex.Message}");
|
||||
m_SocketMsgDelegate?.Invoke(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return m_Handler != null && m_Handler.Connected;
|
||||
}
|
||||
|
||||
public void Send(String data)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 确保 Socket 有效
|
||||
if (m_Handler == null || !m_Handler.Connected)
|
||||
{
|
||||
Console.WriteLine("客户端Socket未连接,无法发送字符串数据");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] byteData = Encoding.UTF8.GetBytes(data);
|
||||
m_Handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), m_Handler);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"客户端发送字符串数据异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void SendCallback(IAsyncResult ar)
|
||||
{
|
||||
try
|
||||
{
|
||||
Socket handler = (Socket)ar.AsyncState;
|
||||
int bytesSent = handler.EndSend(ar);
|
||||
Console.WriteLine($"Sent {bytesSent} bytes to server.");
|
||||
m_SocketMsgDelegate?.Invoke($"发送成功,字节数:{bytesSent}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"客户端发送回调异常:{e.Message}");
|
||||
m_SocketMsgDelegate?.Invoke($"SendCallbackError: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void CloseSocket()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_Handler != null)
|
||||
{
|
||||
if (m_Handler.Connected)
|
||||
{
|
||||
m_Handler.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
m_Handler.Close();
|
||||
}
|
||||
m_Client?.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"关闭客户端Socket异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class IPInfo
|
||||
{
|
||||
public string m_strIPAddr;
|
||||
public int m_nIPPort;
|
||||
public string m_strIPAddr3D;
|
||||
public int m_nIPPort3D;
|
||||
public IPInfo()
|
||||
{
|
||||
m_strIPAddr = "127.0.0.1";
|
||||
m_nIPPort = 8000;
|
||||
m_strIPAddr3D = "127.0.0.1";
|
||||
m_nIPPort3D = 8000;
|
||||
}
|
||||
}
|
||||
|
||||
public class SocketEx
|
||||
{
|
||||
//网口Socket服务
|
||||
public delegate void SocketStringMessage(string str);
|
||||
public delegate void SocketDictMessage(Dictionary<string, string> dict);
|
||||
|
||||
// 两个委托实例,分别处理字符串和字典
|
||||
public SocketStringMessage m_SockStrMsg = null;
|
||||
public SocketDictMessage m_SockDictMsg = null;
|
||||
|
||||
//定义服务器变量
|
||||
public TCPServer m_TcpServer = null; // new TCPServer();
|
||||
//定义客户端变量
|
||||
public TCPClient m_TcpClient = new TCPClient();
|
||||
//服务器或者客户端标志位:true为服务器,false微客户端
|
||||
public bool m_bTcpServer = false;
|
||||
|
||||
//ip地址和端口
|
||||
public IPInfo m_IPInfo = new IPInfo();
|
||||
|
||||
//网口接收消息委托
|
||||
public delegate void SocketMessage(string str);
|
||||
public SocketMessage m_SockMsg = null;
|
||||
|
||||
//析构函数
|
||||
~SocketEx()
|
||||
{
|
||||
CloseSocket(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 网口初始化
|
||||
/// </summary>
|
||||
/// <param name="sockMsg"></param>
|
||||
/// <param name="bTcpServer">bTCPServer: true为服务器;false为客户端</param>
|
||||
/// <returns></returns>
|
||||
public bool InitSocket(SocketStringMessage strMsg, SocketDictMessage dictMsg, bool bTcpServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
m_SockStrMsg = strMsg;
|
||||
m_SockDictMsg = dictMsg;
|
||||
m_bTcpServer = bTcpServer;
|
||||
if (m_bTcpServer)
|
||||
{
|
||||
TCPServer.SocketMessage msg = new TCPServer.SocketMessage(RecvSockMsg);
|
||||
m_TcpServer.InitServer(m_IPInfo.m_strIPAddr, m_IPInfo.m_nIPPort, msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
TCPClient.SocketMessage msg = new TCPClient.SocketMessage(RecvSockMsg);
|
||||
m_TcpClient.InitClient(m_IPInfo.m_strIPAddr, m_IPInfo.m_nIPPort, msg);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string str = ex.ToString();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool InitSocket(SocketMessage sockMsg, bool bTcpServer)
|
||||
{
|
||||
m_SockMsg = sockMsg;
|
||||
return InitSocket(null, null, bTcpServer);
|
||||
}
|
||||
|
||||
//关闭网口
|
||||
public void CloseSocket(bool bTcpServer)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (bTcpServer)
|
||||
m_TcpServer.CloseSocket();
|
||||
else
|
||||
m_TcpClient.CloseSocket();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SocketEx关闭异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
//接收网口信息
|
||||
private void RecvSockMsg(object obj)
|
||||
{
|
||||
if (obj == null) return;
|
||||
|
||||
string rawData = obj.ToString().Trim();
|
||||
try
|
||||
{
|
||||
// 第一步:判断是否为JSON字典(以{开头、以}结尾)
|
||||
if (rawData.StartsWith("{") && rawData.EndsWith("}"))
|
||||
{
|
||||
// 尝试反序列化为Dictionary<string, string>
|
||||
Dictionary<string, string> dictData = JsonConvert.DeserializeObject<Dictionary<string, string>>(rawData);
|
||||
|
||||
// 优先调用字典回调
|
||||
m_SockDictMsg?.Invoke(dictData);
|
||||
Console.WriteLine($"SocketEx 解析出JSON字典:{string.Join("; ", dictData.Select(kv => $"{kv.Key}={kv.Value}"))}");
|
||||
|
||||
// 兼容旧版字符串回调(将字典转为可读字符串)
|
||||
m_SockMsg?.Invoke($"JSON字典:{JsonConvert.SerializeObject(dictData, Formatting.None)}");
|
||||
m_SockStrMsg?.Invoke($"JSON字典:{JsonConvert.SerializeObject(dictData, Formatting.None)}");
|
||||
}
|
||||
else
|
||||
{
|
||||
// 普通字符串,直接传递
|
||||
m_SockStrMsg?.Invoke(rawData);
|
||||
m_SockMsg?.Invoke(rawData);
|
||||
Console.WriteLine($"SocketEx 接收普通字符串:{rawData}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 反序列化失败(不是标准JSON字典),按普通字符串处理
|
||||
string errorMsg = $"数据解析失败:{ex.Message} | 原始数据:{rawData}";
|
||||
m_SockStrMsg?.Invoke(errorMsg);
|
||||
m_SockMsg?.Invoke(errorMsg);
|
||||
Console.WriteLine(errorMsg);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void Send(Dictionary<string, string> dict)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!m_bTcpServer)
|
||||
{
|
||||
m_TcpClient.Send(dict);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("服务器模式下不支持发送JSON字典,请切换为客户端模式");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SocketEx发送JSON字典异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
//发送数据
|
||||
public void Send(string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (m_bTcpServer)
|
||||
{
|
||||
m_TcpServer.Send(str + "\r\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
m_TcpClient.Send(str + "\r\n");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"SocketEx发送异常:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
//获取网口信息
|
||||
public string GetTCPInfo()
|
||||
{
|
||||
return m_bTcpServer ? m_TcpServer.m_strInfo : m_TcpClient.m_strInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user