异步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(客户端)发送上来的抓拍图像,期间要保持通讯,监测数据包并进行处 ...
随机推荐
- ASP.Net MVC——使用 ITextSharp 完美解决HTML转PDF(中文也可以)
前言: 最近在做老师交代的一个在线写实验报告的小项目中,有这么个需求:把学生提交的实验报告(HTML形式)直接转成PDF,方便下载和打印. 以前都是直接用rdlc报表实现的,可这次牵扯到图片,并且更为 ...
- Hibernate中事务的隔离级别设置
Hibernate中事务的隔离级别,如下方法分别为1/2/4/8. 在Hibernate配置文件中设置,设置代码如下
- NGINX引入线程池 性能提升9倍
1. 引言 正如我们所知,NGINX采用了异步.事件驱动的方法来处理连接.这种处理方式无需(像使用传统架构的服务器一样)为每个请求创建额外的专用进程或者线程,而是在一个工作进程中处理多个连接和请求.为 ...
- MySQL常用命令
数据库登陆命令: mysql -uroot -p 2.提示输入密码: 3.登陆成功: 4.数据库修改相关命令: 修改数据库的编码格式: 语法格式为:ALTER {DATABASE|SCHEMA} [ ...
- ORACLE从共享池删除指定SQL的执行计划
Oracle 11g在DBMS_SHARED_POOL包中引入了一个名为PURGE的新存储过程,用于从对象库缓存中刷新特定对象,例如游标,包,序列,触发器等.也就是说可以删除.清理特定SQL的执行计划 ...
- [转] 从知名外企到创业公司做CTO是一种怎样的体验?
这是我近期接受51CTO记者李玲玲采访的一篇文章,分享给大家. 作者:李玲玲来源:51cto.com|2016-12-30 15:47 http://cio.51cto.com/art/201612/ ...
- 项目自动化建构工具gradle 入门1——输出helloWorld
先来一个简单的例子,4个步骤: 1.进入D:\work\gradle\java 目录 ,您电脑没这目录? 那辛苦自己一级一级建立起来吧 新建文件build.gradle,文件内容是: apply p ...
- Centos、Ubuntu 安装 Mono、Jexus
Mono是.NET的跨平台实现 在众多关于语言的争论中,.NET一直被以不能跨平台而诟病,Mono改变了这一现状. 有人当心Mono会涉及版权啥的问题.高深的偶不懂,不过我觉得Unity3D都能用,为 ...
- Hadoop2 自己动手编译Hadoop的eclipse插件
前言: 毕业两年了,之前的工作一直没有接触过大数据的东西,对hadoop等比较陌生,所以最近开始学习了.对于我这样第一次学的人,过程还是充满了很多疑惑和不解的,不过我采取的策略是还是先让环 ...
- vue-router疑惑点记录
以vue-router2.x讲解. 1.定义路由时,某路由对象里同时有component和redirect重定向参数,会怎样处理? 答: 忽略component,直接用redirect的值重定向到新路 ...