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辅助类的更多相关文章

  1. c# socket 心跳 重连

    /// <summary> /// 检查一个Socket是否可连接 /// </summary> /// <param name="socket"&g ...

  2. 动手实现一个较为简单的MQTT服务端和客户端

    项目地址:https://github.com/hnlyf168/DotNet.Framework 昨天晚上大致测试了下 ,490个客户端(一个收一个发)  平均估计每个每秒60个包  使用mqtt协 ...

  3. c# 创建socket连接辅助类-可指定超时时间

    using AD.SocketForm.Model; using NLog; using System; using System.Net.Sockets; using System.Threadin ...

  4. c# 创建socket连接辅助类

    using AD.SocketForm.Model; using NLog; using System; using System.Net; using System.Net.Sockets; nam ...

  5. ByteBuf和相关辅助类

    当我们进行数据传输的时候,往往需要使用到缓冲区,常用的缓冲区就是JDK NIO类库提供的java.nio.Buffer. 实际上,7种基础类型(Boolean除外)都有自己的缓冲区实现,对于NIO编程 ...

  6. Socket Programming in C#--Getting Started

    Getting Started You can argue that one can overcome these shortcomings by multithreading meaning tha ...

  7. Java基于Socket文件传输示例(转)

    最近需要进行网络传输大文件,于是对基于socket的文件传输作了一个初步的了解.在一位网友提供的程序基础上,俺进行了一些加工,采用了缓冲输入/输出流来包装输出流,再采用数据输入/输出输出流进行包装,加 ...

  8. socket的NIO操作

    一.前言 Java中直接使用socket进行通信的场景应该不是很多,在公司的一个项目中有这种需求,所以根据自己的理解和相关资料的参考,基于NIO 实现了一组工具类库,具体的协议还未定义,后续再整理 二 ...

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

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

随机推荐

  1. 完美删除vector的内容与释放内存

    问题:stl中的vector容器常常造成删除假象,这对于c++程序员来说是极其讨厌的,<effective stl>大师已经将之列为第17条,使用交换技巧来修整过剩容量.内存空洞这个名词是 ...

  2. git 操作远程仓库地址

    查看所有远程仓库地址: git remote -v 更改远程仓库地址: git remote set-url origin newUrl 查看某一个远程仓库地址: git remote get-url ...

  3. UVA11770 - Lighting Away

    题目链接 题意:一个有向图,每对一个结点操作.就能够触发连锁反应,使得该结点及它直接或间接指向的点均获得标记,问至少须要操作多少个结点使得全部结点获得标记 思路:有向图的强连通分量.用Tarjan缩点 ...

  4. java开发之随笔记录

    1.java 保留两位小数 DecimalFormat df = new DecimalFormat("#.##"); System.out.println(df.format(1 ...

  5. Jenkins 搭建

    持续集成(CI continuous integration) 可以做什么? 自动构建.定时触发,或由某个事件触发.比如可以做 daily build,或每次代码提交时触发.这样可以最早发现代码编译和 ...

  6. HBase GC日志

    HBase依靠ZooKeeper来感知集群成员及其存活性.假设一个server暂停了非常长时间,它将无法给ZooKeeper quorum发送心跳信息,其他server会觉得这台server已死亡.这 ...

  7. 【BZOJ1414/3705】[ZJOI2009]对称的正方形 二分+hash

    [BZOJ1414/3705][ZJOI2009]对称的正方形 Description Orez很喜欢搜集一些神秘的数据,并经常把它们排成一个矩阵进行研究.最近,Orez又得到了一些数据,并已经把它们 ...

  8. EasyDarwin开源流媒体服务器支持basic基本认证和digest摘要认证解析

    本文转自EasyDarwin开源团队成员ss的博客:http://blog.csdn.net/ss00_2012/article/details/52262621 RTSP认证作为RTSP标准协议的一 ...

  9. Tomcat启动过程中卡住了

    我在部署完项目后,debug启动Tomcat会在中间卡住不继续执行,测试发现在不部署项目的时候Tomcat是可以正常启动的. 控制台信息如下: 十月 25, 2017 10:40:44 上午 org. ...

  10. 浅淡!important对CSS的重要性

    SS中的!important是一个非常重要的属性,有时候发挥着非常大的作用,52CSS.com这方面的知识并不是非常多,我们看下面的文章,对它作比较感观的了解. 前几天写一些CSS代码的时候又难为我了 ...