C#SOCKET类封装,可发送文字图片,断开自动连接(有问题)
来源:互联网 发布:linux怎么进入man 编辑:程序博客网 时间:2024/05/20 18:54
自己的一个比较完整的功能
using System;using System.Collections.Generic;using System.ComponentModel;using System.Threading;using System.Text;using System.IO;using System.Data;using System.Drawing;using System.Net;using System.Net.Sockets;namespace NAL{ public delegate void ReceivedBitmapHandler(Bitmap bitmap); public delegate void ReceivedMsgHandler(string str); public class TransferHandler { private int port = 8089; private IPEndPoint listenEP = null; private IPEndPoint serverEP = null; private Socket _listener = null; private Socket remoteClient = null; private Socket _client = null; public event ReceivedBitmapHandler ReceivedBitmap; public event ReceivedMsgHandler ReceivedMsg; //初始化 public TransferHandler(Socket client) { _client = client; } //初始化IP,端口,SOCKET public TransferHandler(string serverIP,int nport) { serverEP = new IPEndPoint( IPAddress.Parse(serverIP), port); this.port = nport; } //监听 public void StartListen() { listenEP = new IPEndPoint(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address, port); _listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _listener.Bind(listenEP); _listener.Listen(-1); _listener.BeginAccept( new AsyncCallback(AcceptCallback), null); } //监听回调 private void AcceptCallback(IAsyncResult iar) { try { remoteClient = _listener.EndAccept(iar); this.BeginReceive(); } catch (Exception err) { //客户端断开后,自动重新监听 _listener.BeginAccept( new AsyncCallback(AcceptCallback), null); return; } } //执行异步连接 public void BeginConnectServer() { _client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _client.BeginConnect(serverEP, new AsyncCallback(ConnectCallback), null); } //异步连接回调 private void ConnectCallback(IAsyncResult iar) { try { _client.EndConnect(iar); this.BeginReceive(); } catch (Exception err) { //获取连接异常,重新连接 _client.Close(); this.BeginConnectServer(); return; } } //接收信息 public void BeginReceive() { byte[] buffer = new byte[9]; //由于long占8位字节,所以先获取前8位字节数据,标识位1位 IAsyncResult iar = _client.BeginReceive( buffer, 0, buffer.Length, SocketFlags.None, null, null); int len = _client.EndReceive(iar); int offset = 1; int length = BitConverter.ToInt32(buffer, offset); if (buffer[0] == 0) { ReceiveMsg(length); } if (buffer[0] == 1) { //先获取文件长度 ReceiveFile(length); } BeginReceive(); //继续接收 } //接收文件 private void ReceiveFile(long filelen) { MemoryStream ms = new MemoryStream(); int bytesRead = 0; long count = 0; byte[] buffer = new byte[8*1024]; while (count != filelen) { bytesRead = _client.Receive(buffer, buffer.Length, 0); ms.Write(buffer, 0, bytesRead); count += bytesRead; } this._msimage = ms; ReceivedBitmap(new Bitmap(ms)); } //接收消息 private void ReceiveMsg(long strlong) { byte[] buffer = new byte[1024]; string str = string.Empty; _client.Receive(buffer); str = Encoding.Default.GetString(buffer); _strbuffer = Encoding.Default.GetString(buffer); ReceivedMsg(str); } //发送消息 public void SendMsg(string msg) { byte[] arrClientMsg = Encoding.UTF8.GetBytes(msg); byte[] len = BitConverter.GetBytes(msg.Length); byte[] arrClientSendMsg = new byte[arrClientMsg.Length+9]; arrClientSendMsg[0] = 0; Buffer.BlockCopy(len,0,arrClientSendMsg,1,len.Length); Buffer.BlockCopy(arrClientMsg, 0, arrClientSendMsg, 9, arrClientMsg.Length); try { _client.BeginSend(arrClientSendMsg, 0, arrClientSendMsg.Length, SocketFlags.None, new AsyncCallback(SendMsgCallback), null); } catch(SocketException ex) { //可以在此处添加重新连接 string str = ex.ToString(); } } //发送消息回调 private void SendMsgCallback(IAsyncResult iar) { _client.EndSend(iar); } //发送文件 public void SendFile(string filename) { FileInfo fi = new FileInfo(filename); byte[] zero = {1}; byte[] len = BitConverter.GetBytes(fi.Length); byte[] all = new byte[zero.Length+len.Length]; zero.CopyTo(all, 0); len.CopyTo(all, zero.Length); try { //首先把文件长度发送过去 _client.BeginSendFile(filename, all, null, TransmitFileOptions.UseDefaultWorkerThread, new AsyncCallback(SendFileCallback), null); } catch(SocketException ex) { //可以在此处添加重新连接 return; } } //发送文件回调 private void SendFileCallback(IAsyncResult iar) { _client.EndSendFile(iar); } #region 属性 private MemoryStream _msimage = null; private string _strbuffer = null; //图片 流文件 public MemoryStream MSImage { get { return _msimage; } } //字符串 public string StrBuffer { get { return _strbuffer; } } #endregion }}
- C#SOCKET类封装,可发送文字图片,断开自动连接(有问题)
- 问题:解决Android中socket自动断开连接
- C# socket连接断开问题
- websocket自动断开连接问题
- Vxworks下检测关于socket连接关闭的问题-----拔掉网线或超时,自动断开
- Xshell选中文字自动发送Ctrl+C的问题
- MySQL 的自动断开连接问题
- Secure CRT 连接自动断开的问题
- SecureCRT ssh连接自动断开问题
- 解决plsql连接oracle自动断开问题
- ubuntu openssh 连接自动断开问题
- 解决mysql自动断开连接的问题
- oracle连接超时自动断开问题
- 解决MySql8小时自动断开连接问题。
- SecureCRT自动断开连接的问题
- MySQL 自动断开连接的问题
- mysql自动断开连接的问题处理
- mysql workbench自动断开连接问题
- Round-Robin负载均衡算法及其实现原理& Linux下双网卡绑定bond0
- strip
- AdaBoost算法
- Twitter4J Streaming 使用
- Windows eclipse进行C编译开发
- C#SOCKET类封装,可发送文字图片,断开自动连接(有问题)
- marquee属性的使用说明
- SHAREPOINT 2013 - 单一服务器场工作流构建
- vcredist_x86.exe的参数说明
- 注解学习总结
- ubuntu语言设置为英语
- midp事件的存储和获取
- SQLite字段类型使用注意事项
- Internet信息服务(IIS)管理器之常见错误解决办法