天天看點

C# 異步TCP伺服器端用戶端

異步伺服器端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using ClientPub;

namespace ClientPub
{
    public class SocketServer
    {
        private Socket sock;
        private int clientNumb = 0;
        private byte[] byText;
        string receiveMsg;
        IAsyncResult IAccept;
        public List<ConnectionInfo> clientConnections = new List<ConnectionInfo>();

        public delegate void ShowCmdTextHandle(string msg);
        public ShowCmdTextHandle ShowMsgHandle;

        public delegate void ReceiveClientMsgTextHandle(ConnectionInfo client, string msg);
        public ReceiveClientMsgTextHandle ReceiveClientMsgHandle;

        public delegate void ClientConnectedHandle(Socket skt);
        public ClientConnectedHandle ClientConnectedHandler;

        public delegate void ClientDisconnectedHandle(string strIp, int nPort);
        public ClientDisconnectedHandle ClientDisconnectionHandler;


        public delegate void CloseClientConnectionHandle(string strIp, int nPort);
        public CloseClientConnectionHandle CloseClientConnectionHandler;

        /// <summary>
        /// 伺服器監聽tcp端口并接收資訊
        /// </summary>
        public bool BeginServer(int port)
        {
            try
            {
                if (sock!= null && sock.IsBound)
                {
                    ShowMsgHandle("主機正在監聽");
                    return true;
                }
                
                string hostname = System.Net.Dns.GetHostName();
                System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(hostname);//ipEntry.AddressList[0].ToString()
                IPAddress myip = IPAddress.Any;
                IPEndPoint myserver = new IPEndPoint(myip, port);
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sock.Bind(myserver);
                sock.Listen(50);
                IAccept = sock.BeginAccept(new AsyncCallback(Accept), null);
                ShowMsgHandle("主機已準備完畢,等待用戶端連接配接");
            }
            catch (Exception ex)
            {
                MessageBox.Show("異常:開啟TCP服務時發生異常,位于SocketServer.BeginServer(), 詳情:" + ex.Message);
                return false;
            }

            return true;
        }
        /// <summary>
        /// 監聽用戶端
        /// </summary>
        /// <param name="ar"></param>
        private void Accept(IAsyncResult ar)
        {
            try
            {
                if (sock != null)
                {
                    Socket ClientSocket = sock.EndAccept(ar);
                    IPEndPoint ep = ClientSocket.RemoteEndPoint as IPEndPoint;
                    ClientConnectedHandler(ClientSocket);
                    ShowMsgHandle(ep.ToString() + "用戶端連接配接成功");
                    ClientPro(ClientSocket);
                    clientNumb++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("出錯sss:" + ex.Message);
            }
            finally
            {
                if(sock != null)
                    sock.BeginAccept(new AsyncCallback(Accept), null);
            }
        }
        /// <summary>
        /// 連接配接用戶端後做處理過程啟動異步接收
        /// </summary>
        /// <param name="clientSock"></param>
        private void ClientPro(Socket clientSock)
        {
            IPEndPoint ep = clientSock.RemoteEndPoint as IPEndPoint;
            ConnectionInfo ci = new ConnectionInfo();
            ci.Socket = clientSock;
            ci.RveBuffer = new byte[1024];
            lock (clientConnections)
            {
                clientConnections.Add(ci);
            }
            ///向用戶端發送自己的ip和端口,來作為差別的唯一辨別
            //ServerSendAll("伺服器IP");
            //啟動異步接收過程
            clientSock.BeginReceive(ci.RveBuffer, 0, ci.RveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ci);
            //用戶端首次連結成功後,置用戶端狀态為"連接配接成功"
            ci.ClientStatus = ClientStatus.normal;
        }
        /// <summary>
        /// 回調函數做資料處理
        /// </summary>
        /// <param name="result"></param>
        private void ReceiveCallback(IAsyncResult result)
        {
            ConnectionInfo ci = (ConnectionInfo)result.AsyncState;
            if (ci == null || ci.Socket == null || ci.Socket.Connected == false)
            {
                return;
            }
            
            //得到用戶端資訊
            IPEndPoint ep = ci.Socket.RemoteEndPoint as IPEndPoint;
            string ip = ep.Address.ToString();
            int port = ep.Port;

            if (ip == null || ip.Length == 0)
            {
                ip = "0.0.0.0";
                port = 0;
            }
            int bytesRead = 0;

            //檢查用戶端是否已斷開
            try
            {
                bytesRead = ci.Socket.EndReceive(result);
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == 10054)
                {
                    CloseConnection(ci);
                }    
                
                return;
            }
            /*
                若接收到的資料為0,則用戶端斷開連結
            */
            if (bytesRead == 0)
            {
                CloseConnection(ci);
                return;
            }
            
            //處理接收資料
            try
            {
                byText = new byte[bytesRead];
                Array.Copy(ci.RveBuffer, 0, byText, 0, bytesRead);


                string msg = Encoding.Unicode.GetString(byText);
                if (msg.EndsWith(ConstDefine.TCP_END_STRING))
                {
                    receiveMsg += msg.TrimEnd(ConstDefine.TCP_END_STRING.ToCharArray());
                    ci.Data = receiveMsg;
                    ci.ClientStatus = ClientStatus.normal;
                    ReceiveClientMsgHandle(ci, receiveMsg);

                    receiveMsg = "";
                }
                else
                {
                    receiveMsg += msg;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("錯誤:" + ex.Message);
            } 
            finally
            {
                if (ci.Socket.Connected == true)
                {
                    //等待接收資料
                    ci.Socket.BeginReceive(ci.RveBuffer, 0, ci.RveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ci);
                }
            }              
            
        }
        /// <summary>
        /// 關閉目前連結,并從記憶體中清除相應記錄
        /// </summary>
        /// <param name="ci"></param>
        private void CloseConnection(ConnectionInfo ci)
        {
            try
            {
                string strIp = ((IPEndPoint)ci.Socket.RemoteEndPoint).Address.ToString();
                int nPort = ((IPEndPoint)ci.Socket.RemoteEndPoint).Port;

                ci.Socket.Close();
                ShowMsgHandle("用戶端" + strIp+":"+ nPort+ "已經斷開連接配接");
                CloseClientConnectionHandler(strIp, nPort);
            }
            catch (Exception ex)
            {
                MessageBox.Show("斷開連接配接異常:" + ex.Message);
            }
            finally
            {               
                lock (clientConnections)
                {
                    clientConnections.Remove(ci);
                }
            }
        }

        public void CloseConnection(string ip, int port)
        {
            ConnectionInfo ci = FindClient(ip, port);
            if (ci != null)
            {
                CloseConnection(ci);
            }
        }

        public void StopServer()
        {
            List<ConnectionInfo> listTmp = new List<ConnectionInfo>(clientConnections);
            foreach (ConnectionInfo ci in listTmp)
            {
                CloseConnection(ci);
            }

            sock.Close();
            sock = null;
        }

        /// <summary>
        /// 向所有用戶端發送 單個用戶端狀态資料
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool ServerSendAll(byte[] data)
        {
            for (int i = 0; i < clientConnections.Count; i++)
            {
                IPEndPoint ep = clientConnections[i].Socket.RemoteEndPoint as IPEndPoint;
                NetworkStream ns = new NetworkStream(clientConnections[i].Socket);
                try
                {
                    ns.Write(data, 0, data.Length);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("所有用戶端NS資料流對象寫入失敗" + ex.Message);
                    return false;
                }

            } return true;

        }
        /// <summary>
        /// 向所有用戶端發送狀态資料一般狀态
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool ServerSendAll(string msg)
        {
            for (int i = 0; i < clientConnections.Count; i++)
            {
                string serverdata = msg;
                byte[] data = new byte[1024];
                data = Encoding.Unicode.GetBytes(serverdata);
                try
                {
                    for (int j = 0; j < clientConnections.Count; j++)
                    {
                        NetworkStream ns = new NetworkStream(clientConnections[j].Socket);
                        ns.Write(data, 0, data.Length);
                        Thread.Sleep(100);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("所有用戶端NS資料流對象寫入失敗" + ex.Message);
                    return false;
                }

            } return true;

        }

        /// <summary>
        /// 向單獨用戶端發送資料
        /// </summary>
        /// <param name="ci"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool ServerSendOne(ConnectionInfo ci, string msg)
        {
            string serverdata = msg;
            byte[] data = new byte[1024];
            data = Encoding.Unicode.GetBytes(serverdata);

            IPEndPoint ep = ci.Socket.RemoteEndPoint as IPEndPoint;
            NetworkStream ns = new NetworkStream(ci.Socket);
            try
            {
                ns.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show("單獨用戶端NS資料流對象寫入失敗" + ex.Message);
                return false;
            }
            return true;
        }

        public bool ServerSendOne(string ip, int port, string msg)
        {
            ConnectionInfo ci = FindClient(ip, port);
            if (ci == null)
            {
                return false;
            }
            return ServerSendOne(ci, msg);
        }

        /// <summary>
        /// 向單獨用戶端發送資料
        /// </summary>
        /// <param name="ci"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool ServerSendOne(ConnectionInfo ci, byte[] data)
        {
            IPEndPoint ep = ci.Socket.RemoteEndPoint as IPEndPoint;
            NetworkStream ns = new NetworkStream(ci.Socket);
            try
            {
                ns.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show("單獨用戶端NS資料流對象寫入失敗" + ex.Message);
                return false;
            }
            return true;
        }

        public ConnectionInfo FindClient(string ip, int port)
        {
            {
                ConnectionInfo ResultClient = clientConnections.Find(

                delegate(ConnectionInfo client)
                {
                    string strIp = ((IPEndPoint)client.Socket.RemoteEndPoint).Address.ToString();
                    int nPort = ((IPEndPoint)client.Socket.RemoteEndPoint).Port;
                    if (strIp == ip && nPort == port)
                    {
                        return true;
                    }
                    return false;
                });

                return ResultClient;
            }
        }

    }

}
           

異步用戶端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using ClientPub;
using UnityEngine;

namespace ClientPub
{
    // State object for receiving data from remote device.     
    public class SocketClient
    {
        //是否結束接收消息
        bool IsEndRevTcp = false;

        public TcpClient client;
        private NetworkStream ns;
        System.Threading.Thread tRevTcp;
        public string ip { get; set; }//伺服器端ip
        public int port { get; set; } //伺服器端端口
        string localIP;//自己的ip和端口

        string receiveMsg;
        public delegate void ShowCmdTextHandle(string msg);
        public ShowCmdTextHandle ShowMsgHandle;

        public delegate void ReceiveFromServerHandle(string msg);
        public ReceiveFromServerHandle ReceiveMessageFromSeverHandle;     
   
        public SocketClient()
        {
            ip = "127.0.0.1";
            port = 7001;
        }

        public bool StartConnectServer()
        {
            if (client != null && client.Connected)
            {
                return true;
            }
            else
            {

                try
                {
                    client = new TcpClient(ip, port);
                    ns = client.GetStream();
                    if (ns == null)
                    {
                        return false;
                    }
                    IPEndPoint ep = client.Client.RemoteEndPoint as IPEndPoint;
                    IPEndPoint localIEP = (IPEndPoint)client.Client.LocalEndPoint;
                    ShowMsgHandle("已連接配接" + ip + ":" + port + "伺服器");
                    localIP = localIEP.Address.ToString() + ":" + localIEP.Port.ToString();

                    //啟動接受線程
                    tRevTcp = new System.Threading.Thread(RevTcp);
                    tRevTcp.IsBackground = true;
                    tRevTcp.Start();
                    return true;
                }
                catch
                {
                    ShowMsgHandle("連接配接失敗");
                    return false;
                }
            }
        }

        public void CloseConnection()
        {
            try
            {
                IsEndRevTcp = true;
                if (client != null)
                {
                    client.Close();
                    client = null;
                }

               
            }
            catch(Exception ex)
            {
                Debug.Log(ex.Message);
            }
        }
        /// <summary>
        /// 用戶端向伺服器發送資料
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool SendTcp(string data)
        {
            if (ns == null)
            {
                ShowMsgHandle("請先于伺服器進行連接配接");
                return false;
            }
            try
            {
                byte[] datasend = Encoding.Unicode.GetBytes(data);
                ns.Write(datasend, 0, datasend.Length);
                return true;
            }
            catch (Exception ex)
            {
                ShowMsgHandle(ex.Message + "SendTcp");
                return false;
            }
        }
        public bool SendTcp(byte[] data)
        {
            if (ns == null)
            {
                ShowMsgHandle("請先與伺服器進行連接配接");
                return false;
            }
            try
            {
                ns.Write(data, 0, data.Length);
                return true;
            }
            catch (Exception ex)
            {
                ShowMsgHandle(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 用戶端接受資料
        /// </summary>
        public void RevTcp()
        {
            while (true)
            {
                try
                {

                    if (IsEndRevTcp)
                    {
                        break;
                    }
                    ns = client.GetStream();
                    if (ns == null)
                    {
                        return;
                    }
                    byte[] byteRev = new byte[1024];
                    int byteRead = ns.Read(byteRev, 0, 1024);
                    if (byteRead == 0)
                    {
                        return;
                    }
                    byte[] byText = new byte[byteRead];
                    Array.Copy(byteRev, 0, byText, 0, byteRead);
                    //--------------------------------------------這裡做資料處理

                    ClientTreatment(byText);
                    Thread.Sleep(500);
                }
                catch (Exception ex)
                {
                    //如果出現錯誤,把所有控件初始化
                    client = null;
                    ns = null;
                    ShowMsgHandle("已與伺服器斷開");
                    tRevTcp.Abort();
                }
            }
        }

        /// <summary>
        /// 資料處理函數
        /// </summary>
        /// <param name="data"></param>
        public void ClientTreatment(byte[] data)
        {
            //處理接收資料
            try
            {
                string msg = Encoding.Unicode.GetString(data);
                if (msg.EndsWith(ConstDefine.TCP_END_STRING))
                {
                    receiveMsg += msg.TrimEnd(ConstDefine.TCP_END_STRING.ToCharArray());
                    ReceiveMessageFromSeverHandle(receiveMsg);

                    receiveMsg = "";
                }
                else
                {
                    receiveMsg += msg;
                }

            }
            catch (Exception ex)
            {
                Debug.Log("錯誤:" + ex.Message);
            }            
        }
    }
}
           
c# tcp n