C# TCPClient简单示例
生活随笔
收集整理的這篇文章主要介紹了
C# TCPClient简单示例
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
示例
使用方法
參考
使用方法
參考
示例
以下一個(gè)簡單的異步事件TCP客戶端實(shí)現(xiàn)
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading;namespace Leestar54 {/// <summary>/// 自定義回調(diào)事件參數(shù)/// </summary>/// <typeparam name="T">泛型類返回</typeparam>public class TEventArgs<T> : EventArgs{public T Result { get; private set; }public TEventArgs(T obj){this.Result = obj;}}class MyTcpClient{private string md5id;Thread readThread;Thread heartbeatThread;TcpClient tcpClient;NetworkStream ns;//AsyncOperation會(huì)在創(chuàng)建他的上下文執(zhí)行回調(diào)public AsyncOperation AsyncOperation;private static MyTcpClient singleton = null;static readonly object lazylock = new object();#region Event//回調(diào)代理中處理事件public event EventHandler Connected;public event EventHandler<TEventArgs<JObject>> Receive;public event EventHandler<TEventArgs<Exception>> Error;//AsyncOperation回調(diào)代理private SendOrPostCallback OnConnectedDelegate;private SendOrPostCallback OnReceiveDelegate;private SendOrPostCallback OnErrorDelegate;private void OnConnected(object obj){Connected?.Invoke(this, EventArgs.Empty);}private void OnReceive(object obj){Receive?.Invoke(this, new TEventArgs<JObject>((JObject)obj));}private void OnError(object obj){Error?.Invoke(this, new TEventArgs<Exception>((Exception)obj));}#endregion/// <summary>/// 構(gòu)造函數(shù)/// </summary>MyTcpClient(){OnConnectedDelegate = new SendOrPostCallback(OnConnected);OnReceiveDelegate = new SendOrPostCallback(OnReceive);OnErrorDelegate = new SendOrPostCallback(OnError);}/// <summary>/// 單例模式/// </summary>/// <returns></returns>public static MyTcpClient getInstance(){if (singleton == null){lock (lazylock){if (singleton == null){singleton = new MyTcpClient();}}}return singleton;}//當(dāng)前客戶端唯一idpublic string Md5id{get{return md5id;}set{md5id = value;}}/// <summary>/// 連接服務(wù)器/// </summary>public void Connect(){try{tcpClient = new TcpClient("localhost", 9501);if (tcpClient.Connected){ns = tcpClient.GetStream();//開啟兩個(gè)線程長連接,一個(gè)讀取,一個(gè)心跳readThread = new Thread(Read);readThread.IsBackground = true;readThread.Start();heartbeatThread = new Thread(HeartBeat);heartbeatThread.IsBackground = true;heartbeatThread.Start();System.Diagnostics.Debug.WriteLine("服務(wù)器連接成功");this.SendMsg(JObject.FromObject(new{cmd = "connect"}));}}catch (Exception e){this.AsyncOperation.Post(OnErrorDelegate, e);Thread.Sleep(5000);ReConnect();}}/// <summary>/// 讀取接收到的數(shù)據(jù)/// </summary>private void Read(){try{//休眠2秒讓窗口初始化Thread.Sleep(2000);Byte[] readBuffer = new Byte[1024];while (true){int alen = tcpClient.Available;if (alen > 0){Int32 bytes = ns.Read(readBuffer, 0, alen);string responseData = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytes);//為了避免粘包現(xiàn)象,以\r\n作為分割符string[] arr = responseData.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);foreach (var item in arr){if (item != string.Empty){System.Diagnostics.Debug.WriteLine("接受到消息" + item);JObject jobj = JObject.Parse(item);this.AsyncOperation.Post(OnReceiveDelegate, jobj);}}}Thread.Sleep(500);}}catch (Exception e){this.AsyncOperation.Post(OnErrorDelegate, e);}}/// <summary>/// 心跳線程/// </summary>private void HeartBeat(){try{while (true){Thread.Sleep(8000);byte[] wb = System.Text.Encoding.UTF8.GetBytes("+h");ns.Write(wb, 0, wb.Length);}}catch (Exception e){this.AsyncOperation.Post(OnErrorDelegate, e);Thread.Sleep(5000);ReConnect();}}/// <summary>/// 心跳失敗,則網(wǎng)絡(luò)異常,重新連接/// </summary>public void ReConnect(){if (readThread != null){readThread.Abort();}Connect();}public void SendMsg(string msg){byte[] wb = System.Text.Encoding.UTF8.GetBytes(msg);ns.Write(wb, 0, wb.Length);}public void SendMsg(JObject json){SendMsg(json.ToString(Formatting.None));}} }使用方法
MyTcpClient client = MyTcpClient.getInstance(); //保證回調(diào)函數(shù)是在創(chuàng)建他的上下文執(zhí)行(一般是UI線程) client.AsyncOperation = AsyncOperationManager.CreateOperation(null); client.Error += Client_Error; ; client.Receive += Client_Receive; ; client.Connected += Client_Connected; client.Connect();參考
http://www.cnblogs.com/kex1n/p/6502002.html
https://www.codeproject.com/Articles/14265/The-NET-Framework-s-New-SynchronizationContext-Cla
http://www.cnblogs.com/leestar54/p/4591792.html
https://msdn.microsoft.com/zh-cn/library/vs/alm/system.componentmodel.asyncoperationmanager.createoperation(v=vs.85)
附件列表
?
轉(zhuǎn)載于:https://www.cnblogs.com/leestar54/p/7768159.html
總結(jié)
以上是生活随笔為你收集整理的C# TCPClient简单示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从成本角度看Java微服务
- 下一篇: SpringMVC+redis整合