博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
异步Socket 客户端部分
阅读量:4883 次
发布时间:2019-06-11

本文共 9385 字,大约阅读时间需要 31 分钟。

using System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Threading;using System.Windows;using System.IO;namespace IntelliWMS{    ///     /// 客户端Socket    ///     public class ClientSocket    {        #region MyRegion        private StateObject state;        private string host;        private int port;        private int bufferSize;        private Thread GuardThread;                                         //守护线程        private AutoResetEvent m_GuardEvent = new AutoResetEvent(false);    //守护通知事件        public AutoResetEvent m_ReciveEvent = new AutoResetEvent(false);    //接收通知事件        public delegate void Updatedata(string result);        public Updatedata update;        public delegate void Updatelog(string log);        public Updatelog uplog;        public Queue
qBytes = new Queue
(); private static Encoding encode = Encoding.UTF8; FileInfo log = new FileInfo("Log.txt"); ///
/// 类构造函数 /// ///
ip地址 ///
端口 ///
public ClientSocket(string host, int port, int bufferSize = 1024) { this.host = host; this.port = port; this.bufferSize = bufferSize; state = new StateObject(); state.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); state.buffer = new byte[bufferSize]; } public bool Start(bool startGuardThread) { if (state.Connected) return true; try { state.workSocket.BeginConnect(host, port, new AsyncCallback(ConnectCallBack), state); if (startGuardThread) { GuardThread = new Thread(GuardMethod); GuardThread.IsBackground = true; GuardThread.Start(); } return true; } catch (Exception ex) { return false; } } public bool Stop(bool killGuarThread) { CloseSocket(state); if (killGuarThread) { try { GuardThread.Abort(); } catch (Exception ex) { } } return true; } ///
/// 发送 /// ///
///
public bool Send(string data) { try { if (uplog != null) { uplog("[Send] " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\n" + data); using (FileStream fs = log.OpenWrite()) { StreamWriter w = new StreamWriter(fs); w.BaseStream.Seek(0, SeekOrigin.End); w.Write("Send:[{0}] {1}\r\n", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), data); w.Flush(); w.Close(); } } state.workSocket.BeginSend(encode.GetBytes(data), 0, encode.GetBytes(data).Length, SocketFlags.None, new AsyncCallback(SendCallBack), (object)state); } catch (Exception ex) { //m_GuardEvent.Set(); return false; } return true; } ///
/// 发送回调 /// ///
private void SendCallBack(IAsyncResult ar) { StateObject state = ar.AsyncState as StateObject; try { if (state.workSocket != null && state.workSocket.Connected && state.workSocket.EndSend(ar) <= 0) CloseSocket(state); } catch (Exception ex) { MessageBox.Show(ex.Message); } } ///
/// 连接回调 /// ///
private void ConnectCallBack(IAsyncResult ar) { try { StateObject state = ar.AsyncState as StateObject; if (state.workSocket.Connected) //链接成功开始接收数据 { state.workSocket.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(RecvCallBack), state); state.Connected = true; } state.workSocket.EndConnect(ar); } catch (Exception ex) { MessageBox.Show(ex.Message); } } ///
/// 接收回调 /// ///
private void RecvCallBack(IAsyncResult ar) { StateObject state = ar.AsyncState as StateObject; if (!state.Connected) { state.workSocket = null; return; } int readCount = 0; try { //调用这个函数来结束本次接收并返回接收到的数据长度 readCount = state.workSocket.EndReceive(ar); } catch (Exception ex) { return; } try { if (readCount > 0) { byte[] bytes = new byte[readCount]; Array.Copy(state.buffer, 0, bytes, 0, readCount); qBytes.Enqueue(bytes); m_ReciveEvent.Set(); if (update != null) { update(encode.GetString(bytes)); uplog("[Receive] " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\n" + encode.GetString(bytes)); using (FileStream fs = log.OpenWrite()) { StreamWriter w = new StreamWriter(fs); w.BaseStream.Seek(0, SeekOrigin.End); w.Write("Receive:[{0}] {1}\r\n", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), encode.GetString(bytes)); w.Flush(); w.Close(); } } //String2JsonObject(encode.GetString(bytes)); if (state.Connected) state.workSocket.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(RecvCallBack), state); } } catch (Exception ex) { MessageBox.Show(ex.Message); CloseSocket(state); } } ///
/// 关闭连接 /// ///
private void CloseSocket(StateObject state) { state.Connected = false; try { if (state.workSocket != null) state.workSocket.Close(); state.workSocket = null; } catch (Exception ex) { } } ///
/// 守护线程 /// private void GuardMethod() { while (true) { Thread.Sleep(3000); if (state.workSocket == null || state.Connected == false || state.workSocket.Connected == false) { state.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Start(false); } } } ///
/// 提供拆包处理 /// ///
public byte[] Revice() { byte[] buffer = null; if (qBytes.Count > 0) { try { buffer = qBytes.Dequeue(); } catch { } } return buffer; } private void String2JsonObject(string json) { } #endregion } #region 构造容器State ///
/// 构造容器State /// internal class StateObject { ///
/// Client socket. /// public Socket workSocket = null; ///
/// Size of receive buffer. /// public const int BufferSize = 256; ///
/// Receive buffer. /// public byte[] buffer = new byte[BufferSize]; ///
/// Received data string. /// public StringBuilder sb = new StringBuilder(); public bool Connected = false; } #endregion}

以上代码是soket定义

=========================================================================================================

主窗体调用

string ServerIP = "192.168.0.1";            int ServerPort = 4031;             client = new ClientSocket(ServerIP, ServerPort);            client.Start(true);            client.update += Resultdata;  //委托接收Result            client.uplog += updateLog;   //委托显示Send和Result的数据

 

Resultdata

/// /// 服务器Callback/// /// 数据public void Resultdata(string result){    //to do}

 

在主窗体显示Send和Result的数据

public void updateLog(string logdata)        {            this.Dispatcher.Invoke(new Action(delegate            {
Log.Inlines.Add(new Run(logdata + "\n")); scrollViewer1.ScrollToEnd(); })); }

 

转载于:https://www.cnblogs.com/SunsetAzure/p/4942116.html

你可能感兴趣的文章
flask页面中Head标签内容为空问题
查看>>
Centos7 Putty SSH密钥登录
查看>>
HDU 6330--Visual Cube(构造,计算)
查看>>
小说Symbian的签名
查看>>
Objective-C中ORM的运用:实体对象和字典的相互自动转换
查看>>
高级java面试宝典
查看>>
声明,本博客文章均为转载,只为学习,不为其他用途。感谢技术大牛的技术分享,让我少走弯路。...
查看>>
centos7.1下 Docker环境搭建
查看>>
c# 导出Excel
查看>>
Status: Checked in and viewable by authorized users 出现在sharepoint 2013 home 页面
查看>>
python数据预处理
查看>>
Python之路,Day21 - 常用算法学习
查看>>
Android安全-代码安全1-ProGuard混淆处理
查看>>
部署core
查看>>
mysql 时间设置
查看>>
如何在 Xcode 中修改应用的名字
查看>>
有关交换机——熟悉原理是必须的【转载】
查看>>
ACM(数学问题)——UVa202:输入整数a和b(0≤a≤3000,1≤b≤3000),输出a/b的循环小数表示以及循环节长度。...
查看>>
【转】Android 读取doc文件
查看>>
js 数据绑定
查看>>