예제 #1
0
 /// <summary>
 /// 开启TCP通信服务
 /// </summary>
 /// <param name="ipAddress">IP地址</param>
 /// <param name="point">端口号</param>
 /// <param name="listenCount">监听数量</param>
 /// <returns></returns>
 public bool Start(IPAddress ipAddress, int point = 9090, int listenCount = 10)
 {
     try
     {
         if (!TcpIsStart)
         {
             //定义一个套接字用于监听客户端发来的消息,包含三个参数(IP4寻址协议,流式连接,Tcp协议)
             socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             //将IP地址和端口号绑定到网络节点point上
             IPEndPoint iPEndPoint = new IPEndPoint(ipAddress, point);
             //绑定监听IP
             socketServer.Bind(iPEndPoint);
             //套接字的监听队列长度
             socketServer.Listen(listenCount);
             //异步监听客户端连接
             socketServer.BeginAccept(AcceptAsync, socketServer);
             TcpIsStart = true;
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         ErrInfoEvent?.Invoke(ex.Message);
         TcpIsStart = false;
         return(false);
     }
 }
예제 #2
0
        /// <summary>
        /// 异步接收客户端消息
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveDataAsync(IAsyncResult ar)
        {
            Socket socketClient = ar.AsyncState as Socket;

            try
            {
                int readLength = socketClient.EndReceive(ar);
                if (readLength > 0)
                {
                    RecevierEvent?.Invoke(receiveBuffer, socketClient.RemoteEndPoint);
                    Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
                    socketClient.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveDataAsync, socketClient);
                }
                else
                {
                    socketsDic.Remove(socketClient.RemoteEndPoint);
                    clientConnectList.Remove(socketClient.RemoteEndPoint);
                    ConnectChangeEvent?.Invoke();
                }
            }
            catch (Exception ex)
            {
                socketsDic.Remove(socketClient.RemoteEndPoint);
                clientConnectList.Remove(socketClient.RemoteEndPoint);
                ErrInfoEvent?.Invoke(ex.Message);
            }
        }
예제 #3
0
 /// <summary>
 /// 发送消息到服务器
 /// </summary>
 /// <param name="sendBuffer"></param>
 public void Send(byte[] sendBuffer)
 {
     try
     {
         if (!ConnectSucceed)
         {
             return;
         }
         socketClient.BeginSend(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, null, null);
     }
     catch (Exception ex)
     {
         ErrInfoEvent?.Invoke(ex.Message);
     }
 }
예제 #4
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sendBuffer">发送内容(byte[] 类型)</param>
        /// <param name="endPoint">已连接服务器的远端EndPoint类型地址</param>
        public void Send(byte[] sendBuffer, EndPoint endPoint)
        {
            try
            {
                Socket socket = socketsDic[endPoint];

                if (!((socket.Poll(500, SelectMode.SelectRead) && socket.Available == 0)) || !socket.Connected)
                {
                    socket.BeginSend(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, null, null);
                }
            }
            catch (Exception ex)
            {
                ErrInfoEvent?.Invoke(ex.Message);
            }
        }
예제 #5
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="address">本机IP</param>
 /// <param name="point">端口号</param>
 public SocketUdp(IPAddress address, int point)
 {
     try
     {
         receveIP = new IPEndPoint(IPAddress.Any, point);
         localIP  = new IPEndPoint(address, point);
         socket   = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);  //处理发送消息至找不到的IP后出现异常
         socket.Bind(localIP);
         socket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref receveIP, ReceiveDataAsync, null);
         //socket.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveDataAsync, null);
     }
     catch (Exception ex)
     {
         ErrInfoEvent?.Invoke(ex.Message);
     }
 }
예제 #6
0
 /// <summary>
 /// 异步监听客户端
 /// </summary>
 /// <param name="ar"></param>
 private void AcceptAsync(IAsyncResult ar)
 {
     try
     {
         Socket socket = (Socket)ar.AsyncState;
         socket.BeginAccept(AcceptAsync, socket);
         Socket socketClient = socket.EndAccept(ar);
         socketsDic.Add(socketClient.RemoteEndPoint, socketClient);
         clientConnectList.Add(socketClient.RemoteEndPoint);
         ConnectChangeEvent?.Invoke();
         byte[] arrSendMsg = Encoding.UTF8.GetBytes("Connected Successfully!");
         Send(arrSendMsg, socketClient.RemoteEndPoint);
         socketClient.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveDataAsync, socketClient);
     }
     catch (Exception ex)
     {
         ErrInfoEvent?.Invoke(ex.Message);
     }
 }
예제 #7
0
 /// <summary>
 /// 异步接收服务器信息
 /// </summary>
 /// <param name="ar"></param>
 private void ReceiveAsync(IAsyncResult ar)
 {
     try
     {
         Socket receiveSocketAsync = ar.AsyncState as Socket;
         int    readLength         = receiveSocketAsync.EndReceive(ar);
         if (readLength > 0)
         {
             RecevierEvent?.Invoke(receiveBuffer, receiveSocketAsync.RemoteEndPoint);
             Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
             receiveSocketAsync.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveAsync, receiveSocketAsync);
         }
         else
         {
             DisConnect();
             ServerShutdownEvent?.Invoke();
         }
     }
     catch (Exception ex)
     {
         ErrInfoEvent?.Invoke(ex.Message);
     }
 }
예제 #8
0
 /// <summary>
 /// 连接服务器
 /// </summary>
 /// <param name="remoteIp">服务器IP</param>
 /// <param name="remotePort">服务器端口号</param>
 /// <returns></returns>
 public bool Connect(string remoteIp = "127.0.0.1", int remotePort = 9090, int localPort = 9091)
 {
     try
     {
         if (ConnectSucceed)
         {
             return(false);
         }
         socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         socketClient.Bind(new IPEndPoint(IPAddress.Any, localPort));
         this.remoteIp = new IPEndPoint(IPAddress.Parse(remoteIp), remotePort);
         socketClient.Connect(this.remoteIp);
         socketClient.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveAsync, socketClient);
         RefrshServerIsConnected();
         ConnectSucceed = true;
         return(true);
     }
     catch (Exception ex)
     {
         ErrInfoEvent?.Invoke(ex.Message);
         return(false);
     }
 }