异步Socket 客户端部分
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Windows;
using System.IO; namespace IntelliWMS
{
/// <summary>
/// 客户端Socket
/// </summary>
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<byte[]> qBytes = new Queue<byte[]>(); private static Encoding encode = Encoding.UTF8; FileInfo log = new FileInfo("Log.txt"); /// <summary>
/// 类构造函数
/// </summary>
/// <param name="host">ip地址</param>
/// <param name="port">端口</param>
/// <param name="bufferSize"></param>
public ClientSocket(string host, int port, int bufferSize = )
{
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;
} /// <summary>
/// 发送
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
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(, 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), , encode.GetBytes(data).Length, SocketFlags.None, new AsyncCallback(SendCallBack), (object)state);
}
catch (Exception ex)
{
//m_GuardEvent.Set();
return false;
}
return true;
} /// <summary>
/// 发送回调
/// </summary>
/// <param name="ar"></param>
private void SendCallBack(IAsyncResult ar)
{
StateObject state = ar.AsyncState as StateObject;
try
{
if (state.workSocket != null && state.workSocket.Connected && state.workSocket.EndSend(ar) <= )
CloseSocket(state);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} /// <summary>
/// 连接回调
/// </summary>
/// <param name="ar"></param>
private void ConnectCallBack(IAsyncResult ar)
{
try
{
StateObject state = ar.AsyncState as StateObject;
if (state.workSocket.Connected) //链接成功开始接收数据
{
state.workSocket.BeginReceive(state.buffer, , state.buffer.Length, SocketFlags.None, new AsyncCallback(RecvCallBack), state);
state.Connected = true;
}
state.workSocket.EndConnect(ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} /// <summary>
/// 接收回调
/// </summary>
/// <param name="ar"></param>
private void RecvCallBack(IAsyncResult ar)
{
StateObject state = ar.AsyncState as StateObject;
if (!state.Connected)
{
state.workSocket = null;
return;
}
int readCount = ; try
{
//调用这个函数来结束本次接收并返回接收到的数据长度
readCount = state.workSocket.EndReceive(ar);
}
catch (Exception ex)
{
return;
} try
{
if (readCount > )
{
byte[] bytes = new byte[readCount];
Array.Copy(state.buffer, , bytes, , 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(, 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, , state.buffer.Length, SocketFlags.None, new AsyncCallback(RecvCallBack), state);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); CloseSocket(state);
}
} /// <summary>
/// 关闭连接
/// </summary>
/// <param name="state"></param>
private void CloseSocket(StateObject state)
{
state.Connected = false; try
{
if (state.workSocket != null)
state.workSocket.Close();
state.workSocket = null;
}
catch (Exception ex)
{ }
} /// <summary>
/// 守护线程
/// </summary>
private void GuardMethod()
{
while (true)
{
Thread.Sleep();
if (state.workSocket == null || state.Connected == false || state.workSocket.Connected == false)
{
state.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Start(false);
}
}
} /// <summary>
/// 提供拆包处理
/// </summary>
/// <returns></returns>
public byte[] Revice()
{
byte[] buffer = null;
if (qBytes.Count > )
{
try
{
buffer = qBytes.Dequeue();
}
catch { }
}
return buffer;
} private void String2JsonObject(string json)
{ } #endregion
} #region 构造容器State
/// <summary>
/// 构造容器State
/// </summary>
internal class StateObject
{
/// <summary>
/// Client socket.
/// </summary>
public Socket workSocket = null; /// <summary>
/// Size of receive buffer.
/// </summary>
public const int BufferSize = ; /// <summary>
/// Receive buffer.
/// </summary>
public byte[] buffer = new byte[BufferSize]; /// <summary>
/// Received data string.
/// </summary>
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
/// <summary>
/// 服务器Callback
/// </summary>
/// <param name="result">数据</param>
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();
}));
}
异步Socket 客户端部分的更多相关文章
- 异步Socket服务器与客户端
本文灵感来自Andre Azevedo 在CodeProject上面的一片文章,An Asynchronous Socket Server and Client,讲的是异步的Socket通信. S ...
- 《Unity 3D游戏客户端基础框架》多线程异步 Socket 框架构建
引言: 之前写过一个 demo 案例大致讲解了 Socket 通信的过程,并和自建的服务器完成连接和简单的数据通信,详细的内容可以查看 Unity3D -- Socket通信(C#).但是在实际项目应 ...
- GJM :异步Socket [转载]
原帖地址:http://blog.csdn.net/awinye/article/details/537264 原文作者:Awinye 目录(?)[-] 转载请原作者联系 Overview of So ...
- Python简易聊天工具-基于异步Socket通信
继续学习Python中,最近看书<Python基础教程>中的虚拟茶话会项目,觉得很有意思,自己敲了一遍,受益匪浅,同时记录一下. 主要用到异步socket服务客户端和服务器模块asynco ...
- 项目笔记---C#异步Socket示例
概要 在C#领域或者说.net通信领域中有着众多的解决方案,WCF,HttpRequest,WebAPI,Remoting,socket等技术.这些技术都有着自己擅长的领域,或者被合并或者仍然应用于某 ...
- 可扩展多线程异步Socket服务器框架EMTASS 2.0 续
转载自Csdn:http://blog.csdn.net/hulihui/article/details/3158613 (原创文章,转载请注明来源:http://blog.csdn.net/huli ...
- C# 实现的多线程异步Socket数据包接收器框架
转载自Csdn : http://blog.csdn.net/jubao_liang/article/details/4005438 几天前在博问中看到一个C# Socket问题,就想到笔者2004年 ...
- C#实现的异步Socket服务器
介绍 我最近需要为一个.net项目准备一个内部线程通信机制. 项目有多个使用ASP.NET,Windows 表单和控制台应用程序的服务器和客户端构成. 考虑到实现的可能性,我下定决心要使用原生的soc ...
- C# 异步Socket
C# 异步Socket (BeginXXXX)服务器代码 前言: 1.最近维护公司的一个旧项目,是Socket通讯的,主要用于接收IPC(客户端)发送上来的抓拍图像,期间要保持通讯,监测数据包并进行处 ...
随机推荐
- Linux常用命令操作
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...
- 深入浅出Redis-redis哨兵集群
1.Sentinel 哨兵 Sentinel(哨兵)是Redis 的高可用性解决方案:由一个或多个Sentinel 实例 组成的Sentinel 系统可以监视任意多个主服务器,以及这些主服务器属下的所 ...
- js参数arguments的理解
原文地址:js参数arguments的理解 对于函数的参数而言,如下例子 function say(name, msg){ alert(name + 'say' + msg); } say('xiao ...
- Android之Pull解析XML
一.Pull解析方法介绍 除了可以使用SAX和DOM解析XML文件,也可以使用Android内置的Pull解析器解析XML文件.Pull解析器的运行方式与SAX解析器相似.它也是事件触发的.Pull解 ...
- kvm 使用入门详解
kvm 是虚拟化技术的一个典型实现,功能非常强大,使用很方便.kvm 本身主要实现对 CPU 的虚拟化,内存和IO的虚拟化使用了开源软件 qemu,qemu 是纯软件层面的虚拟化,其实就是个模拟器.k ...
- 项目游戏开发日记 No.0x000001
14软二杨近星(2014551622) 既然已经决定了开发软件, 时不时就要练练手, 还要时不时的去寻找素材, 因为开发的人物设定就是DotA2里面的祈求者, 所以, 就去找了他的相关人物图片和模型, ...
- 项目游戏开发日记 No.0x00000
14软二杨近星(2014551622) ---恢复内容开始--- 2016-03-17 从开始迈进软件工程专业, 已经快两年了, 记得当初选择软件的理由是, 我要学去做东西, 我享受开发过程. 两年来 ...
- TypeScript
TypeScript: Angular 2 的秘密武器(译) 本文整理自Dan Wahlin在ng-conf上的talk.原视频地址: https://www.youtube.com/watch? ...
- innodb 自增列重复值问题
1 innodb 自增列出现重复值的问题 先从问题入手,重现下这个bug use test; drop table t1; create table t1(id int auto_increment, ...
- XSS 前端防火墙 —— 无懈可击的钩子
昨天尝试了一系列的可疑模块拦截试验,尽管最终的方案还存在着一些兼容性问题,但大体思路已经明确了: 静态模块:使用 MutationObserver 扫描. 动态模块:通过 API 钩子来拦截路径属性. ...