Exemplo n.º 1
0
        //初始化服务
        public void InitService(string address, string port, ReceiveCallBack recvCall = null)
        {
            try
            {
                m_socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //获取ip地址
                IPAddress ip = IPAddress.Parse(address.Trim());
                //创建端口号
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(port.Trim()));
                //绑定IP地址和端口号
                m_socketWatch.Bind(point);
                //开始监听:设置最大连接请求数目
                m_socketWatch.Listen(10);

                if (recvCall != null)
                {
                    m_recvCallBack = recvCall;
                    string strMsg = "开启监听成功!";
                    byte[] buffer = Encoding.Default.GetBytes(strMsg);
                    m_recvCallBack("", buffer, buffer.Length);
                }

                //创建线程
                AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
                AcceptSocketThread.IsBackground = true;
                AcceptSocketThread.Start(m_socketWatch);
            }
            catch (SocketException ex)
            {
                byte[] buffer = Encoding.Default.GetBytes(ex.Message);
                m_recvCallBack("", buffer, buffer.Length);
            }
        }
Exemplo n.º 2
0
        public void AsyncConnect(string ip, ushort port, NormalNetCallBack connectBack, NormalNetCallBack sendBack, ReceiveCallBack callBackRecv, NormalNetCallBack disConnect)
        {
            //   m_error = ErrorSockets.Success;



            this.m_callBackConnect = connectBack;
            if (clientSocket != null && clientSocket.Connected)
            {
                this.m_callBackConnect(false, ErrorSockets.MutiConnect, "重复连接");

                return;
            }



            this.m_callBackSend       = sendBack;
            this.m_callBackReceive    = callBackRecv;
            this.m_callBackDisConnect = disConnect;



            if (clientSocket == null || !clientSocket.Connected)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress    address   = IPAddress.Parse(ip);
                IPEndPoint   point     = new IPEndPoint(address, port);
                IAsyncResult connectAr = clientSocket.BeginConnect(point, ConnectCallBack, clientSocket);
                if (!WriteDot(connectAr))
                {
                    connectBack(false, ErrorSockets.ConnectTimeOut, "连接超时");
                }
            }
        }
Exemplo n.º 3
0
        // 初始化服务
        public void InitService(string address, string port, ReceiveCallBack recvCall = null)
        {
            try
            {
                m_socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(address.Trim());
                m_socketSend.Connect(ip, Convert.ToInt32(port.Trim()));
                // 实例化回调
                if (recvCall != null)
                {
                    m_recvCallBack = recvCall;
                }

                // 开启一个新的线程不停的接收服务器发送消息的线程
                threadReceive = new Thread(new ThreadStart(Receive));
                // 设置为后台线程
                threadReceive.IsBackground = true;
                threadReceive.Start();
            }
            catch (SocketException ex)
            {
                byte[] buffer = Encoding.Default.GetBytes(ex.Message);
                if (m_recvCallBack != null)
                {
                    m_recvCallBack(buffer, buffer.Length);
                }
            }
        }
Exemplo n.º 4
0
 public SocketClient(string address, int port, ReceiveCallBack callBack)
 {
     this.callBack    = callBack;
     this.address     = address;
     this.port        = port;
     connectionStatus = ConnectionStatus.connecting;
     if (tryConnect())
     {
         startCheckHeartBeat();
         startReceiveMessage();
     }
     else
     {
         startReconnect();
     }
 }
Exemplo n.º 5
0
    //初始化服务器信息
    public void InitServer(ReceiveCallBack cb)
    {
        this.callback = cb;
        // 1.
        Socket server_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        // 2.
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 2222);

        // 3.
        server_socket.Bind(endPoint);
        // 4.
        server_socket.Listen(10);
        // 5.开始异步等待客户端的请求链接
        server_socket.BeginAccept(new System.AsyncCallback(Accept), server_socket);

        this.callback("开启服务器" + endPoint.ToString());
    }
Exemplo n.º 6
0
    // Create an uninitialized server instance.
    // To start the server listening for connection requests
    // call the Init method followed by Start method
    //
    // <param name="numConnections">the maximum number of connections the sample is designed to handle simultaneously</param>
    // <param name="receiveBufferSize">buffer size to use for each socket I/O operation</param>
    // <param name="ReceiveCallBack">接收到消息的回调函数</param>
    public MicrosoftServer(int numConnections, int receiveBufferSize, ReceiveCallBack rcb)
    {
        m_totalBytesRead      = 0;
        m_numConnectedSockets = 0;
        m_numConnections      = numConnections;
        m_receiveBufferSize   = receiveBufferSize;
        receiveCallBack       = rcb;
        // allocate buffers such that the maximum number of sockets can have one outstanding read and
        //write posted to the socket simultaneously
        m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToPreAlloc,
                                            receiveBufferSize);

        m_readPool  = new SocketAsyncEventArgsPool(numConnections);
        m_writePool = new SocketAsyncEventArgsPool(numConnections);
        m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);

        m_buffer = new List <Byte>();
    }
Exemplo n.º 7
0
    //初始化客户端Socket信息
    public void InitClient(string ip, int port, ReceiveCallBack ccb)
    {
        this.clientReceiveCallBack = ccb;
        this.clientSocket          = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        IPAddress  address = IPAddress.Parse(ip);
        IPEndPoint ep      = new IPEndPoint(address, port);

        try
        {
            this.clientSocket.Connect(ep);
        }catch (SocketException e)
        {
            throw e;
        }

        //开始异步等待接收服务端消息
        this.clientSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new System.AsyncCallback(ReceiveFromServer), this.clientSocket);
    }
Exemplo n.º 8
0
        public void StartReceive(string ip, int port, ReceiveCallBack onReceive, ErrorCallBack onError = null)
        {
            Debugger.Log("UDPClient::StartReceive");

            //AddressFamily addressFamily;
            //string connectIP;
            //NetworkHelper.GetIPType(ip, out connectIP, out addressFamily);
            _targetIp  = new IPEndPoint(IPAddress.Parse(ip), port);
            _udpClient = new UdpClient(AddressFamily.InterNetwork);
            if (_SelfIp != null)
            {
                _udpClient.Client.Bind(_SelfIp);
            }
            _udpClient.Client.SendBufferSize    = 1024 * 128;
            _udpClient.Client.ReceiveBufferSize = 1024 * 128;
            _receiveCallBack = onReceive;
            _errorCallBack   = onError;
            _isReceive       = true;
            _recvThread      = new Thread(Receive);
            _recvThread.Start();
        }
Exemplo n.º 9
0
        /// <summary>
        /// 异步接受请求(Server)
        /// </summary>
        /// <param name="callBack">回调函数</param>
        /// <returns>处理结果</returns>
        public void Receive(string remoteEndPoint, ReceiveCallBack callBack = null)
        {
            Byte[] msg = new byte[1024];
            //异步的接受消息
            Socket cSocket = clientConnections[remoteEndPoint];

            cSocket.BeginReceive(msg, 0, msg.Length, SocketFlags.None,
                                 ar =>
            {
                //连接断开时抛出Socket Exception
                try
                {
                    //结束挂起的异步线程
                    cSocket.EndReceive(ar);
                    //还原字符串
                    if (callBack != null)
                    {
                        callBack(cSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(msg).Trim('\0', ' '));
                    }
                    Receive(remoteEndPoint, callBack);
                }
                catch (Exception e)
                {
                    //对于连接断开的异常 移除维持的Socket
                    if (e is SocketException)
                    {
                        clientConnections.Remove(remoteEndPoint);
                        cSocket.Close();
                        OnClientOffline?.Invoke(remoteEndPoint);
                    }
                    else    //对于其他的异常 移除维持的Socket并触发异常事件
                    {
                        OnException?.Invoke(e);
                        clientConnections.Remove(remoteEndPoint);
                        cSocket.Close();
                        OnClientOffline?.Invoke(remoteEndPoint);
                    }
                }
            }, null);
        }
Exemplo n.º 10
0
        private void ReceivedReboot(object data)
        {
            ReceiveCallBack d = new ReceiveCallBack(Rebooted);

            this.Invoke(d, new object[] { data });
        }
Exemplo n.º 11
0
        private void ReceivedFileChange(object data)
        {
            ReceiveCallBack d = new ReceiveCallBack(ShowProgressBar);

            this.Invoke(d, new object[] { data });
        }
Exemplo n.º 12
0
 protected void ReceivedRebootHandle(object data)
 {
      ReceiveCallBack d = new ReceiveCallBack(Rebooting);
      this.Invoke(d, new object[] { data });
 }
Exemplo n.º 13
0
 public void FileTransferHandle(object data)
 {
      ReceiveCallBack d = new ReceiveCallBack(FileTransmitting);
      this.Invoke(d, new object[] { data });
 }
Exemplo n.º 14
0
 /// <summary>
 /// 接受到信息
 /// </summary>
 public static void DoReceive(Action<JObject> action)
 {
     OnReceive += new ReceiveCallBack(action);
 }