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 客户端部分的更多相关文章

  1. 异步Socket服务器与客户端

      本文灵感来自Andre Azevedo 在CodeProject上面的一片文章,An Asynchronous Socket Server and Client,讲的是异步的Socket通信. S ...

  2. 《Unity 3D游戏客户端基础框架》多线程异步 Socket 框架构建

    引言: 之前写过一个 demo 案例大致讲解了 Socket 通信的过程,并和自建的服务器完成连接和简单的数据通信,详细的内容可以查看 Unity3D -- Socket通信(C#).但是在实际项目应 ...

  3. GJM :异步Socket [转载]

    原帖地址:http://blog.csdn.net/awinye/article/details/537264 原文作者:Awinye 目录(?)[-] 转载请原作者联系 Overview of So ...

  4. Python简易聊天工具-基于异步Socket通信

    继续学习Python中,最近看书<Python基础教程>中的虚拟茶话会项目,觉得很有意思,自己敲了一遍,受益匪浅,同时记录一下. 主要用到异步socket服务客户端和服务器模块asynco ...

  5. 项目笔记---C#异步Socket示例

    概要 在C#领域或者说.net通信领域中有着众多的解决方案,WCF,HttpRequest,WebAPI,Remoting,socket等技术.这些技术都有着自己擅长的领域,或者被合并或者仍然应用于某 ...

  6. 可扩展多线程异步Socket服务器框架EMTASS 2.0 续

    转载自Csdn:http://blog.csdn.net/hulihui/article/details/3158613 (原创文章,转载请注明来源:http://blog.csdn.net/huli ...

  7. C# 实现的多线程异步Socket数据包接收器框架

    转载自Csdn : http://blog.csdn.net/jubao_liang/article/details/4005438 几天前在博问中看到一个C# Socket问题,就想到笔者2004年 ...

  8. C#实现的异步Socket服务器

    介绍 我最近需要为一个.net项目准备一个内部线程通信机制. 项目有多个使用ASP.NET,Windows 表单和控制台应用程序的服务器和客户端构成. 考虑到实现的可能性,我下定决心要使用原生的soc ...

  9. C# 异步Socket

    C# 异步Socket (BeginXXXX)服务器代码 前言: 1.最近维护公司的一个旧项目,是Socket通讯的,主要用于接收IPC(客户端)发送上来的抓拍图像,期间要保持通讯,监测数据包并进行处 ...

随机推荐

  1. 【NLP】干货!Python NLTK结合stanford NLP工具包进行文本处理

    干货!详述Python NLTK下如何使用stanford NLP工具包 作者:白宁超 2016年11月6日19:28:43 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的 ...

  2. 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  3. c#比较两个数组的差异

    将DataTable中某一列数据直接转换成数组进行比较,使用的Linq,要引用命名空间using System.Linq; string[] arrRate = dtRate.AsEnumerable ...

  4. Java compiler level does not match解决方法

    从别的地方导入一个项目的时候,经常会遇到eclipse/Myeclipse报Description  Resource Path Location Type Java compiler level d ...

  5. MySQL: Fabric 搭建 HA

    搭建好Fabric之后,就可以在它的基础上创建HA Group. Shard Group.HA+Shard Group等.这里来说明一下如何快速的搭建HA环境. Fabric 192.168.2.23 ...

  6. Linux自动共享USB设备:udev+Samba

    一.概述 公司最近要我实现USB设备插入Ubuntu后,自动共享到网络上,能像Windows共享一样(如\\192.168.1.10)访问里面的内容,不需要写入权限.当时听完这需求,我这新人表示惊呆了 ...

  7. fmt标签把时间戳格式化日期

    jsp页面标签格式化日期 <%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="f" %> ...

  8. Xamarin.Android之SQLiteOpenHelper

    一.前言 在手机中进行网络连接不仅是耗时也是耗电的,而耗电却是致命的.所以我们就需要数据库帮助我们存储离线数据,以便在用户未使用网络的情况下也可以能够使用应用的部分功能,而在需要网络连接的功能上采用提 ...

  9. TFS 2015(Visual Studio Team Foundation Server)的下载和安装

    微软现在所有Visual Studio相关的下载到www.visualstudio.com网站下载是非常方便的 下载地址: 下载ISO版本后,进行安装,由于10-20人的小团队,不需要SharePoi ...

  10. Azure Queue Storage 基本用法 -- Azure Storage 之 Queue

    Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure File Storage 基 ...