コード例 #1
0
 public int Connect(string ip, int port, SocketEventHandler handler)
 {
     try {
         m_ip              = ip;
         m_port            = port;
         this.eventHandler = handler;
         IPAddress  ipAddress  = Dns.GetHostEntry(ip).AddressList[0];
         IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
         client.Connect(ipEndPoint);
         //error_id = NETWORK_CONNECTED;
         BinaryPack header = new BinaryPack(PACKET_HEAD_SIZE);
         client.GetStream().BeginRead(header.buffer, 0, PACKET_HEAD_SIZE, new AsyncCallback(DoReadPacketHeader), header);
         return(0);
     }
     catch (SocketException ex) {
         error_id = NETWORK_CONNECT_ERROR;
         res      = ex.Message;
         return(-1);
     }
     catch (System.Security.SecurityException se) {
         error_id = NETWORK_CONNECT_ERROR;
         res      = se.Message;
         return(-1);
     }
 }
コード例 #2
0
    private void DoReadPacketBody(IAsyncResult ar)
    {
        try{
            int bytesRead = client.GetStream().EndRead(ar);
            if (bytesRead < 1)
            {
                res = "Disconnected";
                Debug.Log("read packet body NETWORK_ERROR1:" + res);
                PostSocketEvent(NETWORK_ERROR, res);
                return;
            }

            BinaryPack body = (BinaryPack)ar.AsyncState;
            body.length += bytesRead;
            if (body.length < body.buffer.Length)
            {
                client.GetStream().BeginRead(body.buffer, body.length, body.buffer.Length - body.length, new AsyncCallback(DoReadPacketBody), body);
            }
            else
            {
                buffers.Enqueue(body.buffer);
                BinaryPack header = new BinaryPack(PACKET_HEAD_SIZE);
                client.GetStream().BeginRead(header.buffer, 0, PACKET_HEAD_SIZE, new AsyncCallback(DoReadPacketHeader), header);
            }
        }
        catch (ArgumentOutOfRangeException ex) {
            error_id = NETWORK_ERROR;
            res      = ex.Message;
            Debug.Log("read packet body NETWORK_ERROR2:" + ex.Message);
            //PostSocketEvent(NETWORK_ERROR, ex.Message);
        }
        catch (IOException eo) {
            error_id = NETWORK_ERROR;
            res      = eo.Message + ", " + eo.GetBaseException().Message;
            Debug.Log("read packet body NETWORK_ERROR3:" + eo.Message + ", " + eo.GetBaseException().Message);
            //PostSocketEvent(NETWORK_ERROR, eo.Message);
        }
    }