C#实现TCP服务端
网上给出的C#实现的基本上都是测试代码,项目使用还是存在一点问题。实在没有办法,自己全新写了一个。不啰嗦,直接上代码。
TCP部分代码下载地址:https://download.csdn.net/download/scy518/15082224
需要整个代码,请私信联系。
测试截图
服务端代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using DeployAssist.UI.Device;
namespace DeployAssist.Net
{
public class TcpSocketServer
{
private DeviceManageForm m_DeviceManageForm = null;
private Socket m_ServerSocket = null;
private IAsyncResult m_IAsyncResult = null;
private Dictionary<string, TcpSocketConnect> m_ConSocketDic = new Dictionary<string, TcpSocketConnect>();
private bool m_Running = false;
public TcpSocketServer(DeviceManageForm dmform)
{
m_DeviceManageForm = dmform;
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="port">端口号</param>
public bool StartServer(string host, int port)
{
try
{
m_Running = true;
//创建负责监听的套接字,注意其中的参数;
m_ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = null;
//创建包含ip和端口号的网络节点对象
if (host == "")
{
endPoint = new IPEndPoint(IPAddress.Any, port);
}
else
{
//将将IP地址字符串转换为IPAddress对象
IPAddress ip = IPAddress.Parse(host);
endPoint = new IPEndPoint(ip, port);
}
//将负责监听的套接字绑定到唯一的ip和端口上
m_ServerSocket.Bind(endPoint);
//设置监听队列的长度
m_ServerSocket.Listen(100);
//开始接受连接,异步
m_IAsyncResult = m_ServerSocket.BeginAccept(new AsyncCallback(OnAccept), m_ServerSocket);
//创建连接超时检测线程
Thread checkConnectTread = new Thread(CheckConnectThread);
checkConnectTread.IsBackground = true;
checkConnectTread.Start();
return true;
}
catch (System.Exception ex)
{
m_DeviceManageForm.DoWirteLog(ex.ToString());
return false;
}
}
/// <summary>
/// 关闭服务
/// </summary>
public void StopServer()
{
//设置停止运行
SetRunning(false);
if (m_ServerSocket != null)
{
m_ServerSocket.Close();
m_ServerSocket = null;
}
lock (m_ConSocketDic)
{
foreach (var item in m_ConSocketDic)
{
//关闭每一个连接
item.Value.CloseSocket();
}
m_ConSocketDic.Clear();
}
}
/// <summary>
/// 接收状态
/// </summary>
public void SetRunning(bool flage)
{
lock (this)
{
m_Running = flage;
}
return;
}
/// <summary>
/// 接收状态
/// </summary>
public bool GetRunning()
{
bool tmprunning = false;
lock (this)
{
tmprunning = m_Running;
}
return tmprunning;
}
/// <summary>
/// 监听客户端请求的方法;
/// </summary>
private void OnAccept(IAsyncResult asyResult)
{
try
{
//一旦监听到一个客户端的请求,就返回一个与该客户端通信的套接字
Socket tcpserver = (Socket)asyResult.AsyncState;
Socket tmpsocket = tcpserver.EndAccept(asyResult);
//将与客户端连接的套接字对象添加到集合中
string remoteEndpoint = tmpsocket.RemoteEndPoint.ToString();
TcpSocketConnect connect = new TcpSocketConnect();
int ret = connect.OpenSocket(this, tmpsocket);
if (ret == 0)
{
m_ConSocketDic.Add(remoteEndpoint, connect);
}
else
{
m_DeviceManageForm.DoWirteLog("Init Connect fail." + remoteEndpoint);
}
//等待新的客户端连接
tcpserver.BeginAccept(new AsyncCallback(OnAccept), tcpserver);
}
catch (System.Exception ex)
{
if (m_ServerSocket != null)
{
m_DeviceManageForm.DoWirteLog(ex.ToString());
}
}
}
/// <summary>
/// 检测连接状态线程
/// </summary>
private void CheckConnectThread()
{
//启动运行
SetRunning(true);
while (GetRunning())
{
try
{
List<string> conkeylist = new List<string>();
lock (m_ConSocketDic)
{
foreach (var dic in m_ConSocketDic)
{
//判断连接是否超时
TcpSocketConnect connect = ((TcpSocketConnect)(dic.Value));
if (connect.CheckTimeOut())
{
connect.CloseSocket();
conkeylist.Add(dic.Key);
}
}
//移除超时会话
foreach (string key in conkeylist)
{
m_ConSocketDic.Remove(key);
}
}
}
catch (System.Exception ex)
{
m_DeviceManageForm.DoWirteLog(ex.ToString());
}
Thread.Sleep(200);
}
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="sokConnectionparn"></param>
public void DoWirteLog(string log)
{
if (m_DeviceManageForm != null)
{
m_DeviceManageForm.DoWirteLog(log);
}
}
/// <summary>
/// 接收数据
/// </summary>
/// <param name="sokConnectionparn"></param>
public void DoReceiveData(string remotePoint, byte[] data, int len)
{
if (m_DeviceManageForm != null)
{
m_DeviceManageForm.DoReceiveData(remotePoint, data, len);
}
}
/// <summary>
/// 发送数据给指定的客户端
/// </summary>
/// <param name="_endPoint">客户端套接字</param>
/// <param name="_buf">发送的数组</param>
/// <returns></returns>
public int DoSendData(string remotePoint, byte[] data, int len)
{
int ret = 0;
TcpSocketConnect connect = new TcpSocketConnect();
if (m_ConSocketDic.TryGetValue(remotePoint, out connect))
{
ret = connect.Send(data, len);
}
else
{
ret = -1 ;
}
return ret;
}
}
}
连接代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using DeployAssist.UI.Device;
using DeployAssist.Util;
namespace DeployAssist.Net
{
public class TcpSocketConnect
{
private TcpSocketServer m_TcpSocketServer = null;
private Socket m_TcpSocket = null;
private Thread m_Thread = null;
private Boolean m_Running = false;
private string m_RemoteIP = "";
private long m_LastTime = 0;
public int OpenSocket(TcpSocketServer tcpserver, Socket sk)
{
m_TcpSocketServer = tcpserver;
m_TcpSocket = sk;
//创建线程接收数据
m_Thread = new Thread(ReceiveDataThread);
m_Thread.IsBackground = true;
m_Thread.Start();
return 0;
}
/// <summary>
/// 关闭连接
/// </summary>
public void CloseSocket()
{
//设置停止
SetRunning(false);
if (m_TcpSocket != null)
{
m_TcpSocket.Shutdown(SocketShutdown.Both);
}
}
/// <summary>
/// 检测是否超时,超时返回true 否则返回false
/// </summary>
/// <param name="buf"></param>
public bool CheckTimeOut(int timeout = 60)
{
int tmptimeout = 60;
if (timeout > 0)
{
tmptimeout = timeout;
}
long now = UtilTool.GetCurrentTimeStamp();
lock (this)
{
if (now - m_LastTime > tmptimeout)
{
return true;
}
}
return false;
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="buf"></param>
public int Send(byte[] buf, int len = 0)
{
if (buf == null)
{
return -1;
}
int ret = 0;
lock (m_TcpSocket)
{
if (m_TcpSocket != null)
{
ret = m_TcpSocket.Send(buf, len, SocketFlags.None);
}
else
{
ret = -2;
}
}
return ret;
}
/// <summary>
/// 获取连接的ip
/// </summary>
/// <returns></returns>
public string GetRemoteIP()
{
lock (m_TcpSocket)
{
if (m_TcpSocket != null && m_RemoteIP == "")
{
IPEndPoint clientipe = (IPEndPoint)m_TcpSocket.RemoteEndPoint;
m_RemoteIP = clientipe.ToString();
}
}
return m_RemoteIP;
}
/// <summary>
/// 接收状态
/// </summary>
public void SetRunning(bool flage)
{
lock (this)
{
m_Running = flage;
}
return;
}
/// <summary>
/// 接收状态
/// </summary>
public bool GetRunning()
{
bool tmprunning = false;
lock (this)
{
tmprunning = m_Running;
}
return tmprunning;
}
/// <summary>
/// 接收数据线程
/// </summary>
private void ReceiveDataThread()
{
//设置接收状态
SetRunning(true);
m_LastTime = UtilTool.GetCurrentTimeStamp();
//定义一个2M的缓存区
byte[] arrRec = new byte[1024 * 1024 * 2];
while (GetRunning())
{
try
{
if (m_TcpSocket == null)
{
break;
}
//接收数据,并返回数据的长度
int length = m_TcpSocket.Receive(arrRec);
if (length > 0)
{
if (m_TcpSocketServer != null)
{
m_TcpSocketServer.DoReceiveData(GetRemoteIP(), arrRec, length);
}
m_LastTime = UtilTool.GetCurrentTimeStamp();
}
}
catch (System.Exception ex)
{
m_TcpSocketServer.DoWirteLog(ex.ToString());
}
Thread.Sleep(100);
}
}
}
}
m_TcpSocketServer.DoReceiveData(GetRemoteIP(), arrRec, length);
}
m_LastTime = UtilTool.GetCurrentTimeStamp();
}
}
catch (System.Exception ex)
{
m_TcpSocketServer.DoWirteLog(ex.ToString());
}
Thread.Sleep(100);
}
}
}
}