C#实现TCP服务端

C#实现TCP服务端

网上给出的C#实现的基本上都是测试代码,项目使用还是存在一点问题。实在没有办法,自己全新写了一个。不啰嗦,直接上代码。

TCP部分代码下载地址:https://download.csdn.net/download/scy518/15082224

需要整个代码,请私信联系。

测试截图

C#实现TCP服务端_第1张图片

服务端代码

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 m_ConSocketDic = new Dictionary();
        private bool m_Running = false;

        public TcpSocketServer(DeviceManageForm dmform)
        {
            m_DeviceManageForm = dmform;
        }

        /// 
        /// 启动服务
        /// 
        /// 端口号
        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;
            }
        }
        /// 
        /// 关闭服务
        /// 
        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();
            }
        }

        /// 
        /// 接收状态
        /// 
        public void SetRunning(bool flage)
        {
            lock (this)
            {
                m_Running = flage;
            }

            return;
        }

        /// 
        /// 接收状态
        /// 
        public bool GetRunning()
        {
            bool tmprunning = false;

            lock (this)
            {
                tmprunning = m_Running;
            }

            return tmprunning;
        }

        /// 
        /// 监听客户端请求的方法;
        /// 
        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());
                }
            }
        }

        /// 
        /// 检测连接状态线程
        /// 
        private void CheckConnectThread()
        {
            //启动运行
            SetRunning(true);

            while (GetRunning())
            {
                try
                {
                    List conkeylist = new List();
                    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);
            }
        }

        /// 
        /// 写日志
        /// 
        /// 
        public void DoWirteLog(string log)
        {
            if (m_DeviceManageForm != null)
            {
                m_DeviceManageForm.DoWirteLog(log);
            }
        }

        /// 
        /// 接收数据
        /// 
        /// 
        public void DoReceiveData(string remotePoint, byte[] data, int len)
        {
            if (m_DeviceManageForm != null)
            {
                m_DeviceManageForm.DoReceiveData(remotePoint, data, len);
            }
        }
        /// 
        /// 发送数据给指定的客户端
        /// 
        /// 客户端套接字
        /// 发送的数组
        /// 
        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;
        }

        /// 
        /// 关闭连接
        /// 
        public void CloseSocket()
        {
            //设置停止
            SetRunning(false);
            if (m_TcpSocket != null)
            {
                m_TcpSocket.Shutdown(SocketShutdown.Both);
            }
        }

        /// 
        /// 检测是否超时,超时返回true 否则返回false
        /// 
        /// 
        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;
        }

        /// 
        /// 发送数据
        /// 
        /// 
        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;
        }

        /// 
        /// 获取连接的ip
        /// 
        /// 
        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;
        }

        /// 
        /// 接收状态
        /// 
        public void SetRunning(bool flage)
        {
            lock (this)
            {
                m_Running = flage;
            }

            return;
        }

        /// 
        /// 接收状态
        /// 
        public bool GetRunning()
        {
            bool tmprunning = false;

            lock (this)
            {
                tmprunning = m_Running;
            }

            return tmprunning;
        }

        /// 
        /// 接收数据线程
        /// 
        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);
        }
    }
}

}


你可能感兴趣的:(C#编程,c#,网络,socket)