socket辅助类
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading; namespace PYC.FileTransfer.Common.SocketHelp000000000000000000000
{
public delegate void NetSockErr(object sender, NetArgs e);
public delegate void NetConnect(object sender, NetArgs e);
public delegate void NetReceiveMsg(object sender, NetArgs e);
public delegate void NetDisConnect(object sender, NetArgs e); public class TCPSockClient : TCPSock
{
public event NetSockErr OnSockErr;
public event NetConnect OnConnect;
public event NetReceiveMsg OnReceiveMsg;
public event NetDisConnect OnDisConnect;
private bool online = false;
public Socket ClientSocket;//客户端网络连接
private Thread ThreadClientReceive;//客户端接收聊天信息线程
private int _ServerPort;
private IPAddress _ServerIP;
private byte[] data = new byte[1024];
private int sent;
public int ServerPort
{
get { return _ServerPort; }
}
public IPAddress ServerIP
{
get { return _ServerIP; }
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="p">服务端端口</param>
/// <param name="ip">服务端IP</param>
/// <param name="f">form</param>
/// <param name="neh">委托</param>
public TCPSockClient(string ip, int port)
{
_ServerPort = port;
_ServerIP = IPAddress.Parse(ip);
} public void Connect(string name)
{
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(_ServerIP, _ServerPort);//建立客户端网络端点
try
{
ClientSocket.Connect(remoteEP);
}
catch (SocketException e)
{
if (OnSockErr != null)
{
args.Msg = "连接远程服务器失败:" + e.Message;
OnSockErr(this, args);
}
return;
}
this_Connect(name);
Thread.Sleep(200);
ThreadClientReceive = new Thread(new ThreadStart(ClientReceive));
ThreadClientReceive.IsBackground = true;
ThreadClientReceive.Start();
} private void this_Connect(string name)
{
Send("Online|" + name);
if (OnConnect != null)
{
NetArgs na = new NetArgs(name);
OnConnect(this, na);
}
} private void ClientReceive()//客户端开始接收信息
{
online = true;
try
{
while (online)
{
if (ClientSocket == null || ClientSocket.Available < 1)
{
Thread.Sleep(200);
continue;
}
data = PreVarReceive(ClientSocket);
string msg = Encoding.Default.GetString(data);
if (msg != "")
{
string[] arr = msg.Split('|');
switch (arr[0])
{
case "Exit":
DisConnect();
return;
break;
default:
if (OnReceiveMsg != null)
{
NetArgs na = new NetArgs(msg);
OnReceiveMsg(this, na);
}
break;
}
}
Thread.Sleep(200);
}
}
catch (Exception e)
{
if (OnSockErr != null)
{
args.Msg = "客户端接收信息失败:" + e.Message;
OnSockErr(this, args);
}
}
} public void Send(string msg)
{
try
{
sent = PreVarSend(ClientSocket, Encoding.Default.GetBytes(msg));
}
catch (Exception e)
{
if (OnSockErr != null)
{
args.Msg = "客户端发送信息失败:" + e.Message;
OnSockErr(this, args);
}
}
} public void DisConnect()
{
Send("Exit");
Thread.Sleep(200);
online = false;
if (ClientSocket.Connected)
{
ClientSocket.Shutdown(SocketShutdown.Both);
}
ClientSocket.Close();
Thread.Sleep(200);
if (ThreadClientReceive.IsAlive)
{
ThreadClientReceive.Abort();
}
if (OnDisConnect != null)
{
NetArgs na = new NetArgs("");
OnDisConnect(this, na);
}
}
} public class TCPSockServer : TCPSock
{
public event NetSockErr OnSockErr;
public event NetConnect OnConnect;
public event NetReceiveMsg OnReceiveMsg;
public event NetDisConnect OnDisConnect;
public bool servering = false;
private Socket SocketListener;
public Socket ClientSocket;
private Thread ThreadListener;//服务器端侦听线程
private Hashtable _clients;
private int _port;
private int _maxBackLog;
private string _serverip;
private byte[] data = new byte[1024];
public Hashtable Clients
{
get { return _clients; }
}
public int Port
{
get { return _port; }
}
public int MaxBackLog
{
get { return _maxBackLog; }
}
public string serverip
{
get { return this._serverip; }
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="p">端口</param>
/// <param name="m">列队</param>
public TCPSockServer(string ip, int p, int m)
{
_serverip = ip;
_port = p;
_maxBackLog = m;
_clients = new Hashtable();
} public void StartServer()
{
ThreadListener = new Thread(new ThreadStart(StartListen));
ThreadListener.IsBackground = true;
ThreadListener.Start();//新开一个线程,用于接收客户端的连接
} public void StopServer()
{
StopListen();//结束侦听,并结束接收信息
} private void StartListen()
{
servering = true;
try
{
SocketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(_serverip), _port);
SocketListener.Bind(remoteEP);
SocketListener.Listen(_maxBackLog);
while (servering)
{
Socket ServerSocket = SocketListener.Accept();
ClientSocket = ServerSocket;
if (_clients.Count >= _maxBackLog || !servering)
{
ServerSocket.Close();
}
else
{
Client client = new Client(ServerSocket);
client.thread = new Thread(new ParameterizedThreadStart(ServerReceive));
client.thread.IsBackground = true;
client.thread.Start(client);
}
Thread.Sleep(200);
}
}
catch (Exception e)
{
if (OnSockErr != null)
{
args.Msg = "服务端开始侦听发生错误:" + e.Message;
OnSockErr(this, args);
}
StopListen();//结束侦听
}
} private void ServerReceive(object ThreadData)
{
Client client = (Client)ThreadData;
try
{
while (client.online && servering)
{
if (client.socket == null || client.socket.Available < 1)
{
Thread.Sleep(200);
continue;
}
data = PreVarReceive(client.socket);
string msg = Encoding.Default.GetString(data);
if (msg != "")
{
string[] arr = msg.Split('|');
switch (arr[0])
{
case "Online":
client.name = arr[1];
if (!Add(client)) return;
break;
case "Exit":
Remove(client);
return;
case "RequestSendFile":
if (OnReceiveMsg != null)
{
NetArgs na = new NetArgs(client.name + "|" + msg);
OnReceiveMsg(this, na);
}
break;
case "ResposeSendFile":
if (OnReceiveMsg != null)
{
NetArgs na = new NetArgs(client.name + "|" + msg);
OnReceiveMsg(this, na);
}
break;
}
}
Thread.Sleep(200);
}
}
catch (Exception e)
{
if (OnSockErr != null)
{
args.Msg = "服务端侦听发生错误:" + e.Message;
OnSockErr(this, args);
}
}
} private bool Add(Client client)
{
if (!_clients.Contains(client.name))
{
_clients.Add(client.name, client);
if (OnConnect != null)
{
NetArgs na = new NetArgs(client.name);
OnConnect(this, na);
}
return true;
}
return false;
} private void Remove(Client client)
{
if (_clients.ContainsKey(client.name))
{
client.online = false;
if (client.socket != null)
{
client.socket.Close();
}
Thread.Sleep(200);
if (client.thread.IsAlive)
{
client.thread.Abort();
}
if (OnDisConnect != null)
{
NetArgs na = new NetArgs(client.name);
OnDisConnect(this, na);
}
Thread.Sleep(200);
_clients.Remove(client.name);
}
} public void Send(Client c, string msg)
{
try
{
data = Encoding.Default.GetBytes(msg);
int sent = PreVarSend(c.socket, data);
}
catch (Exception e)
{
if (OnSockErr != null)
{
args.Msg = "服务端发送信息失败:" + e.Message;
OnSockErr(this, args);
}
}
} private void StopListen()//结束侦听,并结束接收信息
{
servering = false;
lock (_clients.SyncRoot)
{
foreach (DictionaryEntry de in _clients)
{
Client c = (Client)de.Value;
if (c.socket != null)
{
c.socket.Shutdown(SocketShutdown.Both);
c.socket.Close();
}
Thread.Sleep(1000);
if (c.thread.IsAlive)
{
c.thread.Abort();
}
Thread.Sleep(200);
}
_clients.Clear();
}
SocketListener.Close();//关闭服务器侦听连接
Thread.Sleep(1000);
ThreadListener.Abort();//关闭服务器侦听线程
}
} public class Client
{
public bool online;
public Socket socket;
public Thread thread;
private string _name;
private string _remoteIP; public string name
{
set { _name = value; }
get { return _name; }
} public string remoteIP
{
get { return _remoteIP; }
} public Client(Socket s)
{
online = true;
socket = s;
_remoteIP = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString();
}
} public abstract class TCPSock
{
public NetArgs args = new NetArgs(""); public byte[] PreVarReceive(Socket s)
{
int total = 0, recv;
byte[] datasize = new byte[4];
recv = s.Receive(datasize, 0, 4, 0);
int size = BitConverter.ToInt32(datasize, 0);
int dataleft = size;
byte[] data = new byte[size];
while (total < size)
{
recv = s.Receive(data, total, dataleft, 0);
if (recv == 0)
{
data = Encoding.Default.GetBytes("Exit");
break;
}
total += recv;
dataleft -= recv;
}
return data;
} public int PreVarSend(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);
while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}
} private class NetArgs : EventArgs
{
public string Msg;
public NetArgs(string m)
{
Msg = m;
}
} public class UDP
{
public event NetReceiveMsg OnReceiveMsg;
public bool ListenerDone = false;
private int listenPort;
private Thread listenerThread;
private UdpClient listener;
public int ListenPort
{
get { return listenPort; }
} public UDP(int l)
{
listenPort = l;
} public void StartReceive()
{
ListenerDone = false;
listenerThread = new Thread(new ThreadStart(StartListener));
listenerThread.IsBackground = true;
listenerThread.Start();
} private void StartListener()
{
listener = new UdpClient(listenPort);
//任意IP,设端口为0表示任意
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
try
{
while (!ListenerDone)
{
byte[] bytes = listener.Receive(ref groupEP);
string strIP = groupEP.Address.ToString();
string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length);
if (strInfo != null && strInfo != "" && OnReceiveMsg != null)
{
NetArgs na = new NetArgs("来自" + strIP + ":" + strInfo);
OnReceiveMsg(this, na);
}
Thread.Sleep(200);
}
}
catch
{
listener.Close();
}
} public void Send(IPAddress broadcast, string data)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
byte[] sendbuf = Encoding.GetEncoding("gb2312").GetBytes(data);
IPEndPoint ep = new IPEndPoint(broadcast, listenPort);
s.SendTo(sendbuf, ep);
} public void StopReceive()
{
ListenerDone = true;
listener.Close();
Thread.Sleep(200);
if (listenerThread.IsAlive)
{
listenerThread.Abort();
}
}
}
}
socket辅助类的更多相关文章
- c# socket 心跳 重连
/// <summary> /// 检查一个Socket是否可连接 /// </summary> /// <param name="socket"&g ...
- 动手实现一个较为简单的MQTT服务端和客户端
项目地址:https://github.com/hnlyf168/DotNet.Framework 昨天晚上大致测试了下 ,490个客户端(一个收一个发) 平均估计每个每秒60个包 使用mqtt协 ...
- c# 创建socket连接辅助类-可指定超时时间
using AD.SocketForm.Model; using NLog; using System; using System.Net.Sockets; using System.Threadin ...
- c# 创建socket连接辅助类
using AD.SocketForm.Model; using NLog; using System; using System.Net; using System.Net.Sockets; nam ...
- ByteBuf和相关辅助类
当我们进行数据传输的时候,往往需要使用到缓冲区,常用的缓冲区就是JDK NIO类库提供的java.nio.Buffer. 实际上,7种基础类型(Boolean除外)都有自己的缓冲区实现,对于NIO编程 ...
- Socket Programming in C#--Getting Started
Getting Started You can argue that one can overcome these shortcomings by multithreading meaning tha ...
- Java基于Socket文件传输示例(转)
最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解.在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加 ...
- socket的NIO操作
一.前言 Java中直接使用socket进行通信的场景应该不是很多,在公司的一个项目中有这种需求,所以根据自己的理解和相关资料的参考,基于NIO 实现了一组工具类库,具体的协议还未定义,后续再整理 二 ...
- 可扩展多线程异步Socket服务器框架EMTASS 2.0 续
转载自Csdn:http://blog.csdn.net/hulihui/article/details/3158613 (原创文章,转载请注明来源:http://blog.csdn.net/huli ...
随机推荐
- Jememeter和Loadrunner测试MySQL性能
From:http://blog.csdn.net/testingstar/article/details/60579454 MySQL数据库性能测试的方法 前置条件: 安装系统:windows 7 ...
- PHP几种抓取网络数据的常见方法
//本小节的名称为 fsockopen,curl与file_get_contents,具体是探讨这三种方式进行网络数据输入输出的一些汇总.关于 fsockopen 前面已经谈了不少,下面开始转入其它. ...
- Android学习系列(二)布局管理器之线性布局的3种实现方式
转载请注明出处:http://blog.csdn.net/lhy_ycu/article/details/39643669 LinearLayout是Android控件中的线性布局控件,它包括的子控件 ...
- python缺省参数
def test(a,b=22): result=a+b print("resuLt=%d"%result) test(33,33) #缺省参数的意思就是,函数在有参数的情况下,调 ...
- Topcoder SRM625 题解
给出一个字符串求是palindrome和anagram的比率是多少. 知识点: 1 DBL_MAX 64位double的最长数大概是1.7E308,非常大非常大,比long long大上不知多少倍.故 ...
- cvpr2017年的所有论文下载
wget -c -N --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://op ...
- mongoDB之监控工具mongostat及其参数的具体含义
mongostat是mongdb自带的状态检测工具,在命令行下使用.它会间隔固定时间获取mongodb的当前运行状态,并输出.如果你发现数据库突然变慢或者有其他问题的话,你第一手的操作就考虑采用mon ...
- (转)MongoDB在mongo控制台下的基本使用命令
成功启动MongoDB后,再打开一个命令行窗口输入mongo,就可以进行数据库的一些操作. 输入help可以看到基本操作命令: show dbs:显示数据库列表 show collections:显示 ...
- if __name__ == "__main__": 怎么理解?
参考:https://www.cnblogs.com/Neeo/p/9504779.html 总结: 1.防止模块间调用时,执行被调用模块实例化执行,换句话说,就是不要执行调用模块原来实例化的内容 2 ...
- 九度OJ 1100:最短路径 (最短路径)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:4185 解决:619 题目描述: N个城市,标号从0到N-1,M条道路,第K条道路(K从0开始)的长度为2^K,求编号为0的城市到其他城市的 ...