Exemple #1
0
        private bool ProcessError(SocketException ex, EndPoint bufferEndPoint)
        {
            switch (ex.SocketErrorCode)
            {
#if UNITY_IOS && !UNITY_EDITOR
            case SocketError.NotConnected:
#endif
            case SocketError.Interrupted:
            case SocketError.NotSocket:
                return(true);

            case SocketError.ConnectionReset:
            case SocketError.MessageSize:
            case SocketError.TimedOut:
                NetDebug.Write(NetLogLevel.Trace, "[R]Ignored error: {0} - {1}",
                               (int)ex.SocketErrorCode, ex.ToString());
                break;

            default:
                NetDebug.WriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode,
                                    ex.ToString());
                _listener.OnMessageReceived(null, 0, ex.SocketErrorCode, (IPEndPoint)bufferEndPoint);
                break;
            }
            return(false);
        }
Exemple #2
0
    void ServerListen()
    {
        try
        {
            listener = new TcpListener(IPAddress.Parse(IP), port);
            listener.Start();

            Debug.Log("Server on IP: " + IP + " : : Listening for client on port: " + port);

            Byte[] bytes = new Byte[1024];

            while (true)
            {
                using (client = listener.AcceptTcpClient())
                {
                    Debug.Log("Connected to: " + client);
                    using (NetworkStream stream = client.GetStream())
                    {
                        int length;
                        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            var data = new byte[length];
                            Array.Copy(bytes, 0, data, 0, length);

                            string message = Encoding.ASCII.GetString(data);
                            Decode(message);
                        }
                    }
                }
            }
        }
        catch (SocketException SocketException)
        { Debug.Log("Socket exception " + SocketException.ToString()); }
    }
 // Receive thread
 private void ReceiveData()
 {
     receivingClient = new UdpClient(localPort);
     receivingClient.Client.ReceiveTimeout = 500;
     while (true)
     {
         try
         {
             IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
             bytePacket       = receivingClient.Receive(ref anyIP);
             receivedEndPoint = anyIP;
             dataReceived     = true;
         }
         catch (Exception err)
         {
             SocketException sockErr = (SocketException)err; //CAUSES AN ERROR ON QUIT
             if (sockErr.ErrorCode != 10060)
             {
                 Debug.Log("Error receiving packet: " + sockErr.ToString());
                 messageLogger.messageReceived("Error receiving packet: " + sockErr.ToString());
             }
         }
     }
 }
Exemple #4
0
        internal void OnDnsError(Exception ex)
        {
            //
            // Socket exceptions can get thrown due to clients getting closed, sockets being dropped, all kinds of issues
            // So during runtime, almost entirely noise
            //
            SocketException se = ex as SocketException;

            if (se != null)
            {
                if (m_logger.IsTraceEnabled)
                {
                    m_logger.Error("Socket Error {0}", se.ToString());
                }

                return;
            }

            m_logger.Error("Dns Server {0}", ex.ToString());
        }
Exemple #5
0
        private void CloseOrLogSocketException(SocketState state, SocketException sockEx)
        {
            SocketError errorCode = (SocketError)sockEx.ErrorCode;

            switch (errorCode)
            {
            case SocketError.Shutdown:
            case SocketError.ConnectionAborted:
            case SocketError.ConnectionReset:
            case SocketError.Disconnecting:
            case SocketError.NetworkDown:
            case SocketError.NetworkUnreachable:
            case SocketError.NetworkReset:
                Close(state.Client, $"{nameof(SocketException)} ErrorCode: {errorCode}");
                break;

            default:
                Logger.Error(sockEx.ToString());
                Close(state.Client, $"{nameof(SocketException)} ErrorCode: {errorCode}");
                break;
            }
        }
        /// <summary>
        /// Method HandleSocketException.
        /// </summary>
        /// <param name="e">Instance of SocketException.</param>
        private void HandleSocketException(SocketException e)
        {
            if (e.ErrorCode == (int)SocketError.ConnectionReset)
            {
                this.RaiseEvent(this.Disconnected, this._token);
            }

            Debug.WriteLine(string.Format(AsyncSocketClientConstants.ExceptionStringFormat, "DevLib.Net.AsyncSocket.AsyncSocketClient.HandleSocketException", e.Source, e.Message, e.StackTrace, e.ToString()));
            this.OnErrorOccurred(this._token.Socket, new AsyncSocketErrorEventArgs(e.Message, e));
        }
Exemple #7
0
        public void SplashPresenter_StartApplication_Picks_Up_SocketExceptions_When_Starting_WebServer()
        {
            var exception = new SocketException();

            _WebServer.SetupSet(s => s.Online = true).Callback(() => {
                throw exception;
            });
            _WebServer.Setup(a => a.Port).Returns(123);

            _Presenter.Initialise(_View.Object);
            _Presenter.StartApplication();

            _Log.Verify(g => g.WriteLine("Caught exception when starting web server: {0}", exception.ToString()), Times.Once());
            _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotStartWebServerFull, 123), Strings.CannotStartWebServerTitle, false), Times.Once());
            _View.Verify(v => v.ReportProblem(Strings.SuggestUseDifferentPortFull, Strings.SuggestUseDifferentPortTitle, false), Times.Once());
        }
Exemple #8
0
 /// <summary>
 /// Event triggered if a network error occurs while communicating with
 /// the LoginServer.
 /// </summary>
 /// <param name="Exception"></param>
 private void m_LoginClient_OnNetworkError(SocketException Exc)
 {
     MessageBox.Show(Exc.ToString());
     Application.Exit();
 }
Exemple #9
0
        /// <summary>
        /// Queue the send to the Socket buffer with no further delay.
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="length"></param>
        /// <param name="s"></param>
        private void SendNow(SendParameters sendItem)
        {
            Synchronizer.AssertLockIsHeld(m_SendQueue);
            AsyncCallback ac = new AsyncCallback(SendCallback);
            Socket        s  = null;

            while (true)
            {
                try {
                    s = null;
                    using (Synchronizer.Lock(this.m_SocketMap)) {
                        if (m_SocketMap.ContainsKey(sendItem.Id))
                        {
                            s = (Socket)m_SocketMap[sendItem.Id];
                        }
                        else
                        {
                            //I believe this should never happen.
                            Debug.Assert(false, "TCPServerSender.SendNow thinks there is a missing socket map entry for client id: " + sendItem.Id.ToString());
                        }
                    }
                    using (Synchronizer.Lock(m_SendingParticipants)) {
                        if (m_SendingParticipants.ContainsKey(sendItem.Id))
                        {
                            ((ReferenceCounter)m_SendingParticipants[sendItem.Id]).Increment();
                        }
                        else
                        {
                            m_SendingParticipants.Add(sendItem.Id, new ReferenceCounter());
                        }
                        ++m_PendingOutboundMessageCount;
                        s.BeginSend(sendItem.Buffer, 0, sendItem.Length, SocketFlags.None, ac, new SendState(s, sendItem)); //BeginSend won't block.
                    }

                    break;
                }
                catch (Exception e) {
                    using (Synchronizer.Lock(m_SendingParticipants)) {
                        if (m_SendingParticipants.ContainsKey(sendItem.Id))
                        {
                            ((ReferenceCounter)m_SendingParticipants[sendItem.Id]).Decrement();
                        }
                        --m_PendingOutboundMessageCount;
                        Debug.Assert(m_PendingOutboundMessageCount >= 0, "TCPServerSender.SendNow found negative pending message count");
                    }
                    if (e is SocketException)
                    {
                        SocketException se = (SocketException)e;
                        if (se.ErrorCode == 10055)
                        {
                            //Note that this shouldn't happen since we manually control the queue length.
                            Trace.WriteLine("!!!Server Send queue is full.  Sleeping 50 mS", this.GetType().ToString());
                            Thread.Sleep(50);  //Note that sleeping here could cause various bad performance because other threads may be waiting on us..
                        }
                        else
                        {
                            Trace.WriteLine("Send socket exception: " + se.ToString() + " Error code: " + se.ErrorCode.ToString(), this.GetType().ToString());
                            this.DisableClient(sendItem.Id);
                            break;
                        }
                    }
                    else if (e is ObjectDisposedException)
                    {
                        ObjectDisposedException ode = (ObjectDisposedException)e;
                        this.DisableClient(sendItem.Id);
                        Trace.WriteLine(ode.Message, this.GetType().ToString());
                        break;
                    }
                    else
                    {
                        Trace.WriteLine(e.ToString(), this.GetType().ToString());
                        break;
                    }
                }
            }
        }
Exemple #10
0
 /// <summary>
 /// Event triggered if a network error occurs while communicating with
 /// the LoginServer.
 /// </summary>
 /// <param name="Exception"></param>
 private static void m_LoginClient_OnNetworkError(SocketException Exc)
 {
     Console.WriteLine(Exc.ToString());
     Console.ReadLine();
     Environment.Exit(0);
 }
        /// <summary>
        /// Socket异常
        /// </summary>
        /// <param name="e">Instance of SocketException.</param>
        private void HandleSocketException(SocketException e)
        {
            if (e.ErrorCode == (int)SocketError.ConnectionReset || e.ErrorCode == (int)SocketError.ConnectionRefused || e.ErrorCode == (int)SocketError.TimedOut || e.ErrorCode < -1)
            {
                IsConnected = false;
                this.RaiseEvent(this.Disconnected, this.token);
            }

            if (debug)
            {
                Debug.Write(string.Format(errorFormat, "AsyncSocketClient.HandleSocketException", e.Source, e.Message, e.StackTrace, e.ToString()));
            }
            this.OnError(this.token.Socket, new AsyncSocketErrorEventArgs(e.Message, e));
        }
Exemple #12
0
        /// <summary>
        /// Processes actually the HTTP Request.
        /// </summary>
        /// <remarks>Documented by Dev10, 2008-08-07</remarks>
        public void Process()
        {
            myReadBuffer = new byte[client.ReceiveBufferSize];
            String myCompleteMessage = "";
            int    numberOfBytesRead = 0;

#if DEBUG && debug_output
            Debug.WriteLine("Connection accepted. Buffer: " + client.ReceiveBufferSize.ToString());
#endif
            NetworkStream ns = client.GetStream();

            string hValue = "";
            string hKey   = "";

            try
            {
                // binary data buffer index
                int bfndx = 0;

                // Incoming message may be larger than the buffer size.
                do
                {
                    numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length);
                    myCompleteMessage =
                        String.Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

                    // read buffer index
                    int ndx = 0;
                    do
                    {
                        switch (ParserState)
                        {
                        case RState.METHOD:
                            if (myReadBuffer[ndx] != ' ')
                            {
                                HTTPRequest.Method += (char)myReadBuffer[ndx++];
                            }
                            else
                            {
                                ndx++;
                                ParserState = RState.URL;
                            }
                            break;

                        case RState.URL:
                            if (myReadBuffer[ndx] == '?')
                            {
                                ndx++;
                                hKey = "";
                                HTTPRequest.Execute = true;
                                HTTPRequest.Args    = new Hashtable();
                                ParserState         = RState.URLPARM;
                            }
                            else if (myReadBuffer[ndx] != ' ')
                            {
                                HTTPRequest.URL += (char)myReadBuffer[ndx++];
                            }
                            else
                            {
                                ndx++;
                                HTTPRequest.URL = Uri.UnescapeDataString(HTTPRequest.URL);
                                ParserState     = RState.VERSION;
                            }
                            break;

                        case RState.URLPARM:
                            if (myReadBuffer[ndx] == '=')
                            {
                                ndx++;
                                hValue      = "";
                                ParserState = RState.URLVALUE;
                            }
                            else if (myReadBuffer[ndx] == ' ')
                            {
                                ndx++;

                                HTTPRequest.URL = Uri.UnescapeDataString(HTTPRequest.URL);
                                ParserState     = RState.VERSION;
                            }
                            else
                            {
                                hKey += (char)myReadBuffer[ndx++];
                            }
                            break;

                        case RState.URLVALUE:
                            if (myReadBuffer[ndx] == '&')
                            {
                                ndx++;
                                hKey   = Uri.UnescapeDataString(hKey);
                                hValue = Uri.UnescapeDataString(hValue);
                                HTTPRequest.Args[hKey] = HTTPRequest.Args[hKey] != null ? HTTPRequest.Args[hKey] + ", " + hValue : hValue;
                                hKey        = "";
                                ParserState = RState.URLPARM;
                            }
                            else if (myReadBuffer[ndx] == ' ')
                            {
                                ndx++;
                                hKey   = Uri.UnescapeDataString(hKey);
                                hValue = Uri.UnescapeDataString(hValue);
                                HTTPRequest.Args[hKey] = HTTPRequest.Args[hKey] != null ? HTTPRequest.Args[hKey] + ", " + hValue : hValue;

                                HTTPRequest.URL = Uri.UnescapeDataString(HTTPRequest.URL);
                                ParserState     = RState.VERSION;
                            }
                            else
                            {
                                hValue += (char)myReadBuffer[ndx++];
                            }
                            break;

                        case RState.VERSION:
                            if (myReadBuffer[ndx] == '\r')
                            {
                                ndx++;
                            }
                            else if (myReadBuffer[ndx] != '\n')
                            {
                                HTTPRequest.Version += (char)myReadBuffer[ndx++];
                            }
                            else
                            {
                                ndx++;
                                hKey = "";
                                HTTPRequest.Headers = new Hashtable();
                                ParserState         = RState.HEADERKEY;
                            }
                            break;

                        case RState.HEADERKEY:
                            if (myReadBuffer[ndx] == '\r')
                            {
                                ndx++;
                            }
                            else if (myReadBuffer[ndx] == '\n')
                            {
                                ndx++;
                                if (HTTPRequest.Headers["Content-Length"] != null)
                                {
                                    HTTPRequest.BodySize      = Convert.ToInt32(HTTPRequest.Headers["Content-Length"]);
                                    this.HTTPRequest.BodyData = new byte[this.HTTPRequest.BodySize];
                                    ParserState = RState.BODY;
                                }
                                else
                                {
                                    ParserState = RState.OK;
                                }
                            }
                            else if (myReadBuffer[ndx] == ':')
                            {
                                ndx++;
                            }
                            else if (myReadBuffer[ndx] != ' ')
                            {
                                hKey += (char)myReadBuffer[ndx++];
                            }
                            else
                            {
                                ndx++;
                                hValue      = "";
                                ParserState = RState.HEADERVALUE;
                            }
                            break;

                        case RState.HEADERVALUE:
                            if (myReadBuffer[ndx] == '\r')
                            {
                                ndx++;
                            }
                            else if (myReadBuffer[ndx] != '\n')
                            {
                                hValue += (char)myReadBuffer[ndx++];
                            }
                            else
                            {
                                ndx++;
                                if (!HTTPRequest.Headers.ContainsKey(hKey))
                                {
                                    HTTPRequest.Headers.Add(hKey, hValue);
                                }
                                hKey        = "";
                                ParserState = RState.HEADERKEY;
                            }
                            break;

                        case RState.BODY:
                            // Append to request BodyData
                            Array.Copy(myReadBuffer, ndx, this.HTTPRequest.BodyData, bfndx, numberOfBytesRead - ndx);
                            bfndx += numberOfBytesRead - ndx;
                            ndx    = numberOfBytesRead;
                            if (this.HTTPRequest.BodySize <= bfndx)
                            {
                                ParserState = RState.OK;
                            }
                            break;

                        default:
                            ndx++;
                            break;
                        }
                    }while (ndx < numberOfBytesRead);
                }while (ns.DataAvailable);

#if DEBUG && debug_output
                // Print out the received message to the console.
                Debug.WriteLine("Media server received request: " + Environment.NewLine +
                                myCompleteMessage);
#endif

                //Build up the HTTPResponse
                HTTPResponse.version = "HTTP/1.1";

                if (ParserState != RState.OK)
                {
                    HTTPResponse.status = (int)RespState.BAD_REQUEST;
                }
                else
                {
                    HTTPResponse.status = (int)RespState.OK;
                }

                this.HTTPResponse.Headers = new Hashtable();
                this.HTTPResponse.Headers.Add("Server", Parent.Name);
                this.HTTPResponse.Headers.Add("Date", DateTime.Now.ToString("r"));
                this.HTTPResponse.Headers.Add("Cache-Control", "no-cache");
                this.HTTPResponse.Headers.Add("Pragma", "no-cache");
                this.HTTPResponse.Headers.Add("Expires", "-1");

#if DEBUG && debug_output
                //Call the overriden SubClass Method to complete the HTTPResponse Content
                Debug.WriteLine("Preparing reponse.");
#endif
                this.Parent.OnResponse(ref this.HTTPRequest, ref this.HTTPResponse);

                //Create the Header String
                string HeadersString = this.HTTPResponse.version + " " + this.Parent.respStatus[this.HTTPResponse.status] + "\r\n";
                foreach (DictionaryEntry Header in this.HTTPResponse.Headers)
                {
                    HeadersString += Header.Key + ": " + Header.Value + "\r\n";
                }

                HeadersString += "\r\n";
                byte[] bHeadersString = Encoding.ASCII.GetBytes(HeadersString);

#if DEBUG && debug_output
                // Send headers
                Debug.WriteLine("Response headers: " + Environment.NewLine + HeadersString);
#endif
                ns.Write(bHeadersString, 0, bHeadersString.Length);
                ns.Flush();
                // Send body (File)
                if (this.HTTPResponse.mediaStream != null)
                {
                    using (this.HTTPResponse.mediaStream)
                    {
                        byte[] b = new byte[client.SendBufferSize];
                        int    bytesRead;
                        int    totalBytes  = 0;
                        int    totalLength = Convert.ToInt32(this.HTTPResponse.mediaStream.Length);

                        while ((bytesRead = this.HTTPResponse.mediaStream.Read(b, 0, b.Length)) > 0)
                        {
                            ns.Write(b, 0, bytesRead);
                            totalBytes += bytesRead;
#if DEBUG && debug_output
                            Debug.WriteLine(string.Format("Sent {0:0,0} / {1:0,0} KBytes ({2:0.0%}).",
                                                          1.0 * totalBytes / 1024, 1.0 * totalLength / 1024, 1.0 * totalBytes / totalLength));
#endif
                        }

                        ns.Flush();
                        this.HTTPResponse.mediaStream.Close();
                    }
                }
            }
            catch (Exception e)
            {
                if (e is WebException)
                {
                    Trace.WriteLine("A Webexception in CsHTTPRequest was thrown. URI: " + ((WebException)e).Response.ResponseUri.ToString() + Environment.NewLine + e.ToString());
                }
                else
                {
                    Trace.WriteLine("An Exception in CsHTTPRequest was thrown: " + e.ToString());
                }

                if (e.InnerException != null && e.InnerException is SocketException)
                {
                    SocketException se = ((SocketException)e.InnerException);
                    Trace.WriteLine("Socket exception: " + se.ToString());
                    Trace.WriteLine("Error code: " + se.ErrorCode + " SocketErrorCode: " + se.SocketErrorCode);
                }
            }
            finally
            {
                ns.Close();
                client.Close();
                if (this.HTTPResponse.mediaStream != null)
                {
                    this.HTTPResponse.mediaStream.Close();
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// We use one receive thread per socket
        /// </summary>
        /// <param name="o"></param>
        private void ReceiveThread(Object o)
        {
            ReceiveThreadArgs args        = (ReceiveThreadArgs)o;
            NetworkStream     ns          = args.NetStream;
            ParticipantModel  participant = args.Participant;
            Guid     participantId        = participant.Guid;
            EndPoint remoteEP             = args.RemoteEndPoint;

            IFormatter binaryFormatter = new BinaryFormatter();

#if GENERIC_SERIALIZATION
            IGenericSerializable msg = null;
#else
            object msg = null;
#endif

            while (!this.m_Disposed)
            {
                try {
#if GENERIC_SERIALIZATION
                    msg = PacketTypes.DecodeMessage(null, new SerializedPacket(ns));
#else
                    msg = binaryFormatter.Deserialize(ns);  //blocks
#endif
                }
                catch (SerializationException se) {
                    Trace.WriteLine(se.ToString(), this.GetType().ToString());
                    break;
                }
                catch (Exception e) {
                    if (e.InnerException is SocketException)
                    {
                        SocketException se = (SocketException)e.InnerException;
                        if (se.ErrorCode == 10054)
                        {
                            Trace.WriteLine("ReceiveThread detected a disconnected client during NetworkStream.Read: " + remoteEP.ToString(), this.GetType().ToString());
                            break;
                        }
                        else if (se.ErrorCode == 10053)
                        {
                            Trace.WriteLine("ReceiveThread: socket was closed by local host.", this.GetType().ToString());
                            break;
                        }
                        else if (se.ErrorCode == 10004)
                        {
                            Trace.WriteLine("ReceiveThread: a blocking operation was interrupted.", this.GetType().ToString());
                            break;
                        }
                        else
                        {
                            Trace.WriteLine("SocketException in ReceiveThread. remote Endpoint= " + remoteEP.ToString() + " " + se.ToString() + " error code: " + se.ErrorCode.ToString(), this.GetType().ToString());
                            break;
                        }
                    }
                    else
                    {
                        Trace.WriteLine("Exception while reading: " + e.ToString(), this.GetType().ToString());
                        break;
                    }
                }

                lock (m_ReceiveQueue) {
                    m_ReceiveQueue.Enqueue(new ReceiveMessageAndParticipant(msg, participant));
                }
            }

            //Remove the participant from the classroom here.  Notice that the socket for this participant may still be open.
            using (Synchronizer.Lock(m_Classroom.SyncRoot)) {
                m_Classroom.Participants.Remove(participant);
            }

            Trace.WriteLine("ReceiveThread is ending for remote endpoint=" + remoteEP.ToString(), this.GetType().ToString());
        }