本文介绍在上一篇博客中我说了,我将会介绍c#中使用socket和tcplistener和udpclient实现各种同步和异步的tcp和udp服务器,这些都是是我自己花了很多天的时间来总结的,这样一来相信刚接触c#网络编程的朋友们不会像以前的我一样到处出找资料,到处调试。本次我介绍的是使用socket来实现的同步的tcp服务器,同步的tcp服务器和第一篇里面介绍的异步tcp服务器的区别就是,在socket调用accept的时候是否会阻塞。
同步的tcp服务器在接受到一个客户端的请求的时候一般是开启一个线程去处理和这个客户端的通信工作,这种方式的不好的地方就是资源消耗大,但是假如使用线程池的话,事先分配一定数量的线程,性能还是可以。
但是我之所以给出很多方法实现的服务器,主要目的就是想测试哪种情况性能比较不错,就目前来看,异步的模式比较nice,但是其实还有一种iocp模式性能是最好的。。。
socket同步tcp服务器服务端代码
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.net.sockets;
using system.net;
using system.threading;
namespace netframe.net.tcp.sock.synchronous
{
/// <summary>
/// 基于socket实现的同步tcp服务器
/// </summary>
public class sockettcpserver
{
#region fields
/// <summary>
/// 服务器程序允许的最大客户端连接数
/// </summary>
private int _maxclient;
/// <summary>
/// 当前的连接的客户端数
/// </summary>
private int _clientcount;
/// <summary>
/// 服务器使用的异步socket
/// </summary>
private socket _serversock;
/// <summary>
/// 客户端会话列表
/// </summary>
private list<socketclienthandle> _clients;
private bool disposed = false;
#endregion
#region properties
/// <summary>
/// 服务器是否正在运行
/// </summary>
public bool isrunning { get; private set; }
/// <summary>
/// 监听的ip地址
/// </summary>
public ipaddress address { get; private set; }
/// <summary>
/// 监听的端口
/// </summary>
public int port { get; private set; }
/// <summary>
/// 通信使用的编码
/// </summary>
public encoding encoding { get; set; }
#endregion
#region 构造函数
/// <summary>
/// 同步socket tcp服务器
/// </summary>
/// <param name="listenport">监听的端口</param>
public sockettcpserver(int listenport)
: this(ipaddress.any, listenport, 1024)
{
}
/// <summary>
/// 同步socket tcp服务器
/// </summary>
/// <param name="localep">监听的终结点</param>
public sockettcpserver(ipendpoint localep)
: this(localep.address, localep.port, 1024)
{
}
/// <summary>
/// 同步socket tcp服务器
/// </summary>
/// <param name="localipaddress">监听的ip地址</param>
/// <param name="listenport">监听的端口</param>
/// <param name="maxclient">最大客户端数量</param>
public sockettcpserver(ipaddress localipaddress, int listenport, int maxclient)
{
this.address = localipaddress;
this.port = listenport;
this.encoding = encoding.default;
_maxclient = maxclient;
_clients = new list<socketclienthandle>();
_serversock = new socket(localipaddress.addressfamily, sockettype.stream, protocoltype.tcp);
}
#endregion
#region method
/// <summary>
/// 启动服务器
/// </summary>
public void start()
{
if (!isrunning)
{
isrunning = true;
_serversock.bind(new ipendpoint(this.address, this.port));
thread thread = new thread(startlisten);
thread.start();
}
}
/// <summary>
/// 开始进行监听
/// </summary>
private void startlisten()
{
_serversock.listen(1024);
socketclienthandle handle;
while (isrunning)
{
if (_clientcount >= _maxclient)
{
//todo 客户端过多异常
raiseotherexception(null);
}
else
{
socket clientsock = _serversock.accept();
_clientcount++;
//todo 创建一个处理客户端的线程并启动
handle = new socketclienthandle(clientsock);
_clients.add(handle);
//使用线程池来操作
threadpool.queueuserworkitem(new waitcallback(handle.receviedata));
//thread pthread;
//pthread = new thread(new threadstart(client.receviedata));
//pthread.start();
//这里应该使用线程池来进行
}
}
}
/// <summary>
/// 停止服务器
/// </summary>
public void stop()
{
if (isrunning)
{
isrunning = false;
_serversock.close();
//todo 关闭对所有客户端的连接
}
}
/// <summary>
/// 发送函数
/// </summary>
public void send(string msg, socketclienthandle client)
{
//todo
}
/// <summary>
/// 关闭一个与客户端之间的会话
/// </summary>
/// <param name="handle">需要关闭的客户端会话对象</param>
public void close(socketclienthandle handle)
{
if (handle != null)
{
_clients.remove(handle);
handle.dispose();
_clientcount--;
//todo 触发关闭事件
}
}
/// <summary>
/// 关闭所有的客户端会话,与所有的客户端连接会断开
/// </summary>
public void closeallclient()
{
foreach (socketclienthandle handle in _clients)
{
close(handle);
}
_clientcount = 0;
_clients.clear();
}
#endregion
#region 事件
/// <summary>
/// 与客户端的连接已建立事件
/// </summary>
public event eventhandler<socketeventargs> clientconnected;
/// <summary>
/// 与客户端的连接已断开事件
/// </summary>
public event eventhandler<socketeventargs> clientdisconnected;
/// <summary>
/// 触发客户端连接事件
/// </summary>
/// <param name="state"></param>
private void raiseclientconnected(socketclienthandle handle)
{
if (clientconnected != null)
{
clientconnected(this, new socketeventargs(handle));
}
}
/// <summary>
/// 触发客户端连接断开事件
/// </summary>
/// <param name="client"></param>
private void raiseclientdisconnected(socket client)
{
if (clientdisconnected != null)
{
clientdisconnected(this, new socketeventargs("连接断开"));
}
}
/// <summary>
/// 接收到数据事件
/// </summary>
public event eventhandler<socketeventargs> datareceived;
private void raisedatareceived(socketclienthandle handle)
{
if (datareceived != null)
{
datareceived(this, new socketeventargs(handle));
}
}
/// <summary>
/// 数据发送事件
/// </summary>
public event eventhandler<socketeventargs> completedsend;
/// <summary>
/// 触发数据发送事件
/// </summary>
/// <param name="state"></param>
private void raisecompletedsend(socketclienthandle handle)
{
if (completedsend != null)
{
completedsend(this, new socketeventargs(handle));
}
}
/// <summary>
/// 网络错误事件
/// </summary>
public event eventhandler<socketeventargs> neterror;
/// <summary>
/// 触发网络错误事件
/// </summary>
/// <param name="state"></param>
private void raiseneterror(socketclienthandle handle)
{
if (neterror != null)
{
neterror(this, new socketeventargs(handle));
}
}
/// <summary>
/// 异常事件
/// </summary>
public event eventhandler<socketeventargs> otherexception;
/// <summary>
/// 触发异常事件
/// </summary>
/// <param name="state"></param>
private void raiseotherexception(socketclienthandle handle, string descrip)
{
if (otherexception != null)
{
otherexception(this, new socketeventargs(descrip, handle));
}
}
private void raiseotherexception(socketclienthandle handle)
{
raiseotherexception(handle, "");
}
#endregion
#region close 未实现
#endregion
#region 释放
/// <summary>
/// performs application-defined tasks associated with freeing,
/// releasing, or resetting unmanaged resources.
/// </summary>
public void dispose()
{
dispose(true);
gc.suppressfinalize(this);
}
/// <summary>
/// releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release
/// both managed and unmanaged resources; <c>false</c>
/// to release only unmanaged resources.</param>
protected virtual void dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
try
{
stop();
if (_serversock != null)
{
_serversock = null;
}
}
catch (socketexception)
{
//todo 异常
}
}
disposed = true;
}
}
#endregion
}
}
对客户端操作封装的handle类
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.net.sockets;
namespace netframe.net.tcp.sock.synchronous
{
/// <summary>
/// socket 服务器用于处理客户端连接封装的客户端处理类
/// </summary>
public class socketclienthandle:idisposable
{
/// <summary>
/// 与客户端相关联的socket
/// </summary>
private socket _client;
/// <summary>
/// 标识是否与客户端相连接
/// </summary>
private bool _is_connect;
public bool isconnect
{
get { return _is_connect; }
set { _is_connect = value; }
}
/// <summary>
/// 数据接受缓冲区
/// </summary>
private byte[] _recvbuffer;
public socketclienthandle(socket client)
{
this._client = client;
_is_connect = true;
_recvbuffer = new byte[1024 * 1024 * 2];
}
#region method
/// <summary>
/// 接受来自客户端发来的数据
/// </summary>
public void receviedata(object state)
{
int len = -1;
while (_is_connect)
{
try
{
len = _client.receive(_recvbuffer);
}
catch (exception)
{
//todo
}
}
}
/// <summary>
/// 向客户端发送数据
/// </summary>
public void senddata(string msg)
{
byte[] data = encoding.default.getbytes(msg);
try
{
//有一种比较好的写法
_client.send(data);
}
catch (exception)
{
//todo 处理异常
}
}
#endregion
#region 事件
//todo 消息发送事件
//todo 数据收到事件
//todo 异常处理事件
#endregion
#region 释放
/// <summary>
/// performs application-defined tasks associated with freeing,
/// releasing, or resetting unmanaged resources.
/// </summary>
public void dispose()
{
_is_connect = false;
if (_client != null)
{
_client.close();
_client = null;
}
gc.suppressfinalize(this);
}
#endregion
}
}
socket同步tcp服务器的时间参数类
using system;
using system.collections.generic;
using system.linq;
using system.text;
namespace netframe.net.tcp.sock.synchronous
{
/// <summary>
/// 同步socket tcp服务器事件类
/// </summary>
public class socketeventargs : eventargs
{
/// <summary>
/// 提示信息
/// </summary>
public string _msg;
/// <summary>
/// 客户端状态封装类
/// </summary>
public socketclienthandle _handle;
/// <summary>
/// 是否已经处理过了
/// </summary>
public bool ishandled { get; set; }
public socketeventargs(string msg)
{
this._msg = msg;
ishandled = false;
}
public socketeventargs(socketclienthandle handle)
{
this._handle = handle;
ishandled = false;
}
public socketeventargs(string msg, socketclienthandle handle)
{
this._msg = msg;
this._handle = handle;
ishandled = false;
}
}
}
以上就是c#网络编程系列文章(二)之socket实现同步tcp服务器的内容。