异步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(客户端)发送上来的抓拍图像,期间要保持通讯,监测数据包并进行处 ...
随机推荐
- CRL快速开发框架系列教程五(使用缓存)
本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...
- python 数据类型 ---文件一
1.文件的操作流程: 打开(open), 操作(read,write), 关闭(close) 下面分别用三种方式打开文件,r,w,a 模式 . "a"模式将不会覆盖原来的文件内容, ...
- Java实现Excel中的NORMSDIST函数和NORMSINV函数
由于工作中需要将Excel中的此两种函数转换成java函数,从而计算内部评级的资本占用率和资本占用金额.经过多方查阅资料和整理,总结出如下两个转换方法 标准正态分布累计函数NORMSDIST: pub ...
- OSGi规范的C#实现开源
这是大约在3-4年前完成的一个C#实现的OSGi框架,实现的过程参照了OSGi规范与与一些实现思路(感谢当时的那些资料与项目),此框架虽然仅在几个小型项目有过实际的应用,但OSGi的规范实现还是相对比 ...
- Kotlin类:功能更强、而更简洁(KAD 03)
作者:Antonio Leiva 时间:Dec 7, 2016 原文链接:http://antonioleiva.com/classes-kotlin/ Kotlin类尽可能简单,这样用较少的代码完成 ...
- django 第三天 有关库使用
项目中经常会用到第三方的lib和app,有些lib和app会进行不断更新,更新后可能会存在冲突,因此可以创建externals目录,下面欧app和libs.app存放django-cms,haysta ...
- welcome to my cnblog
博客园总算开通了,以后就分享自己的东西,和大家交流.
- BRDF 光照模型
http://blog.csdn.net/liu_lin_xm/article/details/4846144
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): da.huying.usermanag ...
- Jquery网页元素里面的操作以及JSON
如果网页里面有复选框,下拉列表Jquery怎么来操作,主要是怎么选取数据,就是取选中值,第二个是设置哪一项选中 <script src="jquery-1.11.2.min.js&qu ...