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);
            }            
        }
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值