模拟服务端
private string TcpServiceControl(string value) { // 1.按照模拟工具上看 先new一个tcp服务 Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //申请端口,绑定ip IPAddress iPAddress = IPAddress.Parse(_appConfig.ApplictionSettings.ControlTcpIP); IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, Convert.ToInt32(_appConfig.ApplictionSettings.ControlTcpPort)); //绑定ip和端口 serverSocket.Bind(iPEndPoint); //开始监听端口 设置50防止服务器崩溃,设置0表示不限制数量 serverSocket.Listen(0);//传递挂起的连接队列的最大长度 //接收客户端信息 程序会暂停 直到由一个客户端连接过来才会继续向下运行 Socket clientSocket = serverSocket.Accept();//接收一个客户端连接,返回一个socket用来和客户端通讯 //向客户端发送一条数据 byte[] data = System.Text.Encoding.UTF8.GetBytes(value); clientSocket.Send(data); //接收客户端一条消息 byte[] databuffer = new byte[1024];//接收时先定义一个数组 int count = clientSocket.Receive(databuffer);//知道数组中前count个是接收到的数据 String hex = Encoding.ASCII.GetString(databuffer, 0, count); //string msgREceive = System.Text.Encoding.UTF8.GetString(databuffer, 0, count); //Console.WriteLine(msgREceive); //Console.ReadKey();//程序终止的太快,方便观察输出 //关闭服务器端 clientSocket.Close();//关闭与客户端的连接 serverSocket.Close();//关闭服务器自身的连接 return hex; }
模拟客户端
private static void NewMethod() { // 1.按照模拟工具上看 先new一个tcp服务 //Parse将字符串转换为IP地址类型 IPAddress myIP = IPAddress.Parse("192.168.88.1"); //构造一个TcpClient类对象,TCP客户端 TcpClient client = new TcpClient(); //与TCP服务器连接 client.Connect(myIP, 10067); Console.WriteLine("服务器已经连接...请输入对话内容..."); //创建网络流,获取数据流 NetworkStream stream = client.GetStream(); //读数据流对象 StreamReader sr = new StreamReader(stream); //写数据流对象 StreamWriter sw = new StreamWriter(stream); while (true) { string msg = Console.ReadLine(); sw.WriteLine(msg); sw.Flush(); //刷新流 Console.WriteLine("服务器:" + sr.ReadLine()); } client.Close(); Console.Read(); // 2.输入的数据转化为 16 进制传输 }
将服务注入asp.net core webapi中
public class WebSocketService : IWebSocketService { private static AppConfig _appConfig; private static Socket _serverSocket; private static Socket _clientSocket; private static bool _IsClientSendData = false; private static byte[] buffer = new byte[100]; private readonly IDataCollectionExpandService _dataCollectionExpandService; public WebSocketService(AppConfig appConfig, IDataCollectionExpandService dataCollectionExpandService) { _appConfig = appConfig; _dataCollectionExpandService = dataCollectionExpandService; } public void SocketServiceOpen() { try { System.Timers.Timer Read_Timer; //设置定时间隔(毫秒为单位) 5s Read_Timer = new System.Timers.Timer(10000); Read_Timer.AutoReset = true; Read_Timer.Enabled = true; Read_Timer.Elapsed += new ElapsedEventHandler((s, e) => TimerOutCallBack(s, e)); Read_Timer.Start(); } catch (Exception ex) { Console.WriteLine("socket启动失败" + ex.Message); } } private void TimerOutCallBack(object s, ElapsedEventArgs e) { Console.WriteLine("----->>>轮询监测"); if (_serverSocket == null) { SocketStartService(); } if (_clientSocket != null && _IsClientSendData == true) { IsSocketSend(_clientSocket); } } private void IsSocketSend(Socket s) { try { _clientSocket.Send(HexStringToBytes("11 01 00 00 00 08 3F 5C")); } catch (Exception ex) { _IsClientSendData = false; Console.WriteLine(ex.Message); SocketRestart(); } } // 检查一个Socket是否可连接 //private bool IsSocketConnected(Socket s) //{ // #region 再舍弃 // //return !((s.Poll(1000, SelectMode.SelectRead) && (s.Available == 0)) || !s.Connected); // #endregion // #region 先舍弃 // //bool blockingState = client.Blocking; // //try // //{ // // byte[] tmp = new byte[1]; // // client.Blocking = false; // // client.Send(tmp, 0, 0); // // return true; // //} // //catch (SocketException e) // //{ // // // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的 // // if (e.NativeErrorCode.Equals(10035)) // // return false; // // else // // return true; // //} // //finally // //{ // // client.Blocking = blockingState; // 恢复状态 // //} // #endregion //} /// <summary> /// socket 服务重启 /// </summary> private void SocketRestart() { //if (_clientSocket.Poll(1000, SelectMode.SelectRead)) //{ // _clientSocket.Close(); // _serverSocket.Close(); // _clientSocket.Dispose(); // _serverSocket.Dispose(); // SocketStartService(); // Console.WriteLine("socket服务重启"); // return; //} _clientSocket.Close(); _serverSocket.Close(); _clientSocket.Dispose(); _serverSocket.Dispose(); Console.WriteLine("socket服务重启中……待连接"); SocketStartService(); Console.WriteLine("socket服务重启成功"); return; } private void SocketStartService() { Console.WriteLine("进入SocketServiceOpen"); // 1.按照模拟工具上看 先new一个tcp服务 _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //申请端口,绑定ip IPAddress iPAddress = IPAddress.Parse(_appConfig.ApplictionSettings.ControlTcpIP); IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, Convert.ToInt32(_appConfig.ApplictionSettings.ControlTcpPort)); //绑定ip和端口 _serverSocket.Bind(iPEndPoint); //开始监听端口 设置50防止服务器崩溃,设置0表示不限制数量 _serverSocket.Listen(0);//传递挂起的连接队列的最大长度 ////接收客户端信息 程序会暂停 直到由一个客户端连接过来才会继续向下运行 _clientSocket = _serverSocket.Accept(); //接收一个客户端连接,返回一个socket用来和客户端通讯 _clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket); _IsClientSendData = true; } /// <summary> /// 回调函数的接收 /// </summary> /// <param name="result"></param> public void ReceiveCallback(IAsyncResult result) { try { Socket ts = (Socket)result.AsyncState; ts.EndReceive(result); result.AsyncWaitHandle.Close(); Console.WriteLine("收到消息:{0}", Encoding.ASCII.GetString(buffer)); //string data = ByteArrayToHexString(buffer); string data = ToHexStrFromByte(buffer); Console.WriteLine(data); if (!string.IsNullOrEmpty(data)) { _dataCollectionExpandService.SetTASSocketDataAsync(data); } //清空数据,重新开始异步接收 buffer = new byte[buffer.Length]; ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts); } catch (Exception ex) { Console.WriteLine("socket服务异常" + ex.Message); } } /// <summary> /// 是否有客户端连接 /// </summary> /// <returns></returns> public bool IsSocketClinet() { bool isSocketClinet = true; if (_clientSocket == null) { isSocketClinet = false; } return isSocketClinet; } /// <summary> /// 发送数据到客户端 /// </summary> /// <param name="value"></param> /// <returns></returns> public async Task SendSocketServiceMessages(byte[] value) { //byte[] data = System.Text.Encoding.UTF8.GetBytes(value); //_publicSocket = _clientSocket; _clientSocket.Send(value); //_clientSocket.BeginAccept(AcceptCallback,null); //接收客户端一条消息 //byte[] databuffer = new byte[1024];//接收时先定义一个数组 //int count = _clientSocket.Receive(databuffer);//知道数组中前count个是接收到的数据 //return Encoding.ASCII.GetString(databuffer, 0, count); } public string ByteArrayToHexString(byte[] data) { StringBuilder sb = new StringBuilder(data.Length * 3); foreach (byte b in data) { sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' ')); } return sb.ToString().ToUpper(); } /// <summary> /// 字节数组转16进制字符串:空格分隔 /// </summary> /// <param name="byteDatas"></param> /// <returns></returns> public string ToHexStrFromByte(byte[] byteDatas) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < byteDatas.Length; i++) { builder.Append(string.Format("{0:X2} ", byteDatas[i])); } return builder.ToString().Trim(); } public static byte[] HexStringToBytes(string hs) { string[] strArr = hs.Trim().Split(' '); byte[] b = new byte[strArr.Length]; //逐个字符变为16进制字节数据 for (int i = 0; i < strArr.Length; i++) { b[i] = Convert.ToByte(strArr[i], 16); } //按照指定编码将字节数组变为字符串 return b; } }
注入
services.AddSingleton(typeof(IWebSocketService), typeof(WebSocketService)); WebSocketService webSocketService = new WebSocketService(_appConfig); Thread thread = new Thread(() => webSocketService.SocketServiceOpen()); thread.Start();