EndReceive() public method

public EndReceive ( IAsyncResult asyncResult ) : int
asyncResult IAsyncResult
return int
Esempio n. 1
0
        /// <summary>
        /// Gets triggered when the socket receives something
        /// </summary>
        /// <param name="ar">async result</param>
        private void OnReceiveCallback(IAsyncResult ar)
        {
            try
            {
                if (_socket == null)
                {
                    return;
                }

                var bytesRead = _socket.EndReceive(ar);

                if (bytesRead <= 0)
                {
                    Close();
                    return;
                }

                /**
                 * I thought the problem was this line because it triggers the command handler without checking if the packet
                 *   is "complete" it only checks if "its not null"
                 */
                //Console.WriteLine("BytesRead: {0} | Packet Length: {1}", bytesRead, BitConverter.ToInt16(new byte[] {_readBuffer[1], _readBuffer[0]}, 0));
                //if (BitConverter.ToInt16(new byte[] {_readBuffer[1], _readBuffer[0]}, 0) + 2 == bytesRead)
                //{
                //    OnReceiveData(_readBuffer);
                //}// what happens if it's incomplete just ignores it and waits for the next packet.. i'm not sure if that should work as expected
                OnReceiveData(_readBuffer);

                //Setup over
                _readBuffer = new byte[BufferSize];
                _socket.BeginReceive(_readBuffer, 0, _readBuffer.Length, 0, OnReceiveCallback, this);
            }
            catch { Close(); }
        }
 private static void receiveCallback(IAsyncResult result)
 {
     System.Net.Sockets.Socket socket = null;
     try
     {
         socket = (System.Net.Sockets.Socket)result.AsyncState;
         if (socket.Connected)
         {
             int received = socket.EndReceive(result);
             if (received > 0)
             {
                 byte[] data = new byte[received];
                 Buffer.BlockCopy(buffer, 0, data, 0, data.Length); //copy the data from your buffer
                                                                    //DO ANYTHING THAT YOU WANT WITH data, IT IS THE RECEIVED PACKET!
                                                                    //Notice that your data is not string! It is actually byte[]
                                                                    //For now I will just print it out
                 Console.WriteLine("Server Üzenete: " + Encoding.UTF8.GetString(data));
                 socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket);
             }
             else
             { //completely fails!
                 Console.WriteLine("receiveCallback is failed!");
                 socket.Close();
             }
         }
     }
     catch (Exception e)
     { // this exception will happen when "this" is be disposed...
         Console.WriteLine("receiveCallback is failed! " + e.ToString());
     }
 }
Esempio n. 3
0
 protected void handleAsyncReceive(IAsyncResult res)
 {
     try
     {
         if (socket != null && socket.Connected)
         {
             int bytesReceived = socket.EndReceive(res);
             if (bytesReceived > 0)
             {
                 byte[] temp = new byte[bytesReceived];
                 Array.Copy(message, temp, bytesReceived);
                 startReceive();                         //listen for new connections again
                 digestIncomingBuffer(temp);
                 return;
             }
         }
     }
     catch (Exception)
     {
         //((ILogger)server).error("Receiving from server failed. Error message: " + ex.Message);
     }
     handshaked = false;
     if (OnClose != null)
     {
         OnClose();
     }
     closeSignal.Set();
 }
Esempio n. 4
0
        private void ReceiveAsync(Action <byte[]> Action)
        {
            try
            {
                //Console.WriteLine("[1]");
                NativeSocket.BeginReceive(Buffers, SocketFlags.None, (IAsyncResult) =>
                {
                    //Console.WriteLine("[2]");
                    SocketError SocketError;
                    var Readed = NativeSocket.EndReceive(IAsyncResult, out SocketError);

                    //Console.WriteLine("[3]");

                    //Console.WriteLine(Readed);
                    var ArrayBuffer = Buffers[0];
                    var Buffer      = new byte[Readed];
                    Array.Copy(ArrayBuffer.Array, ArrayBuffer.Offset, Buffer, 0, Buffer.Length);
                    //Buffers[0].
                    Core.EnqueueTask(() =>
                    {
                        Action(Buffer);
                    });
                    ReceiveAsync(Action);
                }, null);
            }
            catch (SocketException SocketException)
            {
                SocketExceptionThrown(SocketException);
            }
        }
 private static void receiveCallback(IAsyncResult result)
 {
     System.Net.Sockets.Socket socket = null;
     try {
         socket = (System.Net.Sockets.Socket)result.AsyncState;
         if (socket.Connected)
         {
             int received = socket.EndReceive(result);
             if (received > 0)
             {
                 receiveAttempt = 0;
                 byte[] data = new byte[received];
                 Buffer.BlockCopy(buffer, 0, data, 0, data.Length);                         //There are several way to do this according to https://stackoverflow.com/questions/5099604/any-faster-way-of-copying-arrays-in-c in general, System.Buffer.memcpyimpl is the fastest
                 //DO ANYTHING THAT YOU WANT WITH data, IT IS THE RECEIVED PACKET!
                 //Notice that your data is not string! It is actually byte[]
                 //For now I will just print it out
                 Console.WriteLine("Server: " + Encoding.UTF8.GetString(data));
                 socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket);
             }
             else if (receiveAttempt < MAX_RECEIVE_ATTEMPT)                         //not exceeding the max attempt, try again
             {
                 ++receiveAttempt;
                 socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket);
             }
             else                         //completely fails!
             {
                 Console.WriteLine("receiveCallback is failed!");
                 receiveAttempt = 0;
                 clientSocket.Close();
             }
         }
     } catch (Exception e) {             // this exception will happen when "this" is be disposed...
         Console.WriteLine("receiveCallback is failed! " + e.ToString());
     }
 }
Esempio n. 6
0
            void ReadCallback(IAsyncResult ar)
            {
                Enqueue(delegate {
                    if (socket == null)
                    {
                        return;
                    }

                    if (readTimer != null)
                    {
                        readTimer.Stop();
                        readTimer.Start();
                    }

                    SocketError error;
                    int len = socket.EndReceive(ar, out error);

                    if (error != SocketError.Success)
                    {
                        RaiseError(new SocketException());
                    }
                    else if (len == 0)
                    {
                        RaiseEndOfStream();
                    }
                    else
                    {
                        RaiseData(new ByteBuffer(receiveBuffer, 0, len));
                        HandleRead();
                    }
                });
            }
    private void OnReceive(IAsyncResult ar)
    {
        try {
            System.Net.Sockets.Socket clientSocket =
                (System.Net.Sockets.Socket)ar.AsyncState;
            int bytecount = clientSocket.EndReceive(ar);

            // now we have the retrieved data in byteData
            Message incomingMsg = new Message(byteData, bytecount);

            // resume receiving incoming information
            clientSocket.BeginReceive(byteData,
                                      0,
                                      byteData.Length,
                                      SocketFlags.None,
                                      new AsyncCallback(OnReceive),
                                      clientSocket);

            processIncomingMessage(incomingMsg, clientSocket);
        }
        catch (Exception ex) {
            log("Something went wrong during receiving data:");
            log(ex.Message);
        }
    }
Esempio n. 8
0
    private void OnReceive(IAsyncResult ar)
    {
        try {
            int bytecount = clientSocket.EndReceive(ar);
            // decode the thing into a message
            Message msg = new Message(byteData, bytecount);
            switch (msg.command)
            {
            case Command.DescribeDrinks:
                // log ("somestuff"); // for some reason, this doesn't work.
                //log(msg.parameter);
                updateDrinksFromServer(msg.parameter);
                break;

            default:
                log("Unknown message type");
                break;
            }
            clientSocket.BeginReceive(byteData,
                                      0,
                                      byteData.Length,
                                      SocketFlags.None,
                                      new AsyncCallback(OnReceive),
                                      null);
        }
        catch (ObjectDisposedException) {
            log("ObjectDisposedException");
        }
        catch (Exception ex) {
            log("Something went wrong during recieving:");
            log(ex.Message);
        }
    }
    private void DataArrival(System.IAsyncResult oResult)
    {
        log.Info("Data Arrive");

        System.Net.Sockets.Socket oSocket = (System.Net.Sockets.Socket)oResult.AsyncState;
        try
        {
            int nBytes = System.Convert.ToInt32(oSocket.EndReceive(oResult));
            if (nBytes > 0)
            {
                string sData = (string)(System.Text.Encoding.ASCII.GetString(oString, 0, nBytes));
                if (TCPDataArrivalEvent != null)
                {
                    TCPDataArrivalEvent(sData);
                }
                f_WaitForData(oSocket);
            }
            else
            {
                oSocket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                oSocket.Close();
                log.Info("Socket Closed");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            log.Error("Error:" + ex.Message);
        }
    }
Esempio n. 10
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                int nReceived = mainSocket.EndReceive(ar);
                //Analyze the bytes received...
                ParseData(byteData, nReceived);

                if (bContinueCapturing)
                {
                    byteData = new byte[4096];

                    //Another call to BeginReceive so that we continue to receive the incoming
                    //packets
                    mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                                            new AsyncCallback(OnReceive), null);
                }
            }
            catch (ObjectDisposedException)
            {
            }
            catch (Exception ex)
            {
                WriteLog("{0}\r\n{1}", ex.Message, ex.StackTrace);
                //MessageBox.Show(ex.Message, "MJsniffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 11
0
    public void OnReceived(IAsyncResult ar)
    {
        try
        {
            System.Net.Sockets.Socket sock = (System.Net.Sockets.Socket)ar.AsyncState;

            int nBytesRec = sock.EndReceive(ar);
            if (nBytesRec > 0)
            {
                // Read the message
                int bytesRead = sock.Receive(m_byBuff, BitConverter.ToInt32(m_msg_header, 0), SocketFlags.None);
                // Wrote the data to the List
                string received = Encoding.ASCII.GetString(m_byBuff, 0, bytesRead);

                JObject obj = JObject.Parse(received);
                if (obj["type"].ToString() == "message")
                {
                    string severity = obj["severity"].ToString();
                    string message  = obj["message"].ToString();

                    if (severity == "info")
                    {
                        WriteLog(message, tagInfo);
                    }
                    else if (severity == "warning")
                    {
                        WriteLog(message, tagWarning);
                    }
                    else if (severity == "error")
                    {
                        WriteLog(message, tagError);
                    }
                    else if (severity == "debug")
                    {
                        WriteLog(message, tagDebug);
                    }
                }
                else
                {
                    WriteLog("Unknown response from server\n", tagInfo);
                }

                // If the connection is still usable restablish the callback
                Receive(sock);
            }
            else
            {
                // If no data was recieved then the connection is probably dead
                WriteLog("Server closed connection\n", tagInfo);
                sock.Shutdown(SocketShutdown.Both);
                sock.Close();
            }
        }
        catch (Exception ex)
        {
            WriteLog("Unknown error during receive\n", tagInfo);
        }
    }
Esempio n. 12
0
 /**
  * Ends asynchronous receiving.
  *
  * @param asyncResult
  *   The IAsyncResult returned from the asynchronous reading.
  */
 private int EndReceive(System.IAsyncResult asyncResult)
 {
     try {
         return(penguinSocks.EndReceive(asyncResult));
     }catch (System.Exception readEx) {
         Out.Logger.WriteOutput("Could not end receive: " + readEx.Message);
         return(0);
     }
 }
        private void ReceiveCallback(IAsyncResult ar)
        {
            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)ar.AsyncState;
            Int32 read = 0;

            try
            {
                read = socket.EndReceive(ar);
            }
            catch (ObjectDisposedException)
            {
                // do nothing
                return;
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode != SocketError.OperationAborted &&
                    ex.SocketErrorCode != SocketError.Interrupted &&
                    ex.SocketErrorCode != SocketError.ConnectionReset)
                {
                    EndReceive(ex);
                }
                else
                {
                    // closed
                    Processor.Remove(this);
                }
                return;
            }
            catch (Exception ex)
            {
                EndReceive(ex);
                return;
            }

            if (read > 0)
            {
                if (ReuseBuffer)
                {
                    EndReceive(IoBuffer.Wrap(_readBuffer, 0, read));
                }
                else
                {
                    IoBuffer buf = IoBuffer.Allocate(read);
                    buf.Put(_readBuffer, 0, read);
                    buf.Flip();
                    EndReceive(buf);
                }
            }
            else
            {
                // closed
                //Processor.Remove(this);
                this.FilterChain.FireInputClosed();
            }
        }
Esempio n. 14
0
        private static void BeginReceiveServer(Socket client)
        {
            var buffer = new byte[0xFFFF];
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, result =>
                                                                            {
                                                                                OnReceiveServer(buffer, client.EndReceive(result));

                                                                                BeginReceiveServer(client);
                                                                            }, buffer);
        }
Esempio n. 15
0
        private static void BeginReceiveClient(Socket server)
        {
            var buffer = new byte[0xFFFF];
            server.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, result =>
                                                                            {
                                                                                OnReceiveClient(buffer, server.EndReceive(result));

                                                                                BeginReceiveClient(server);
                                                                            }, buffer);
        }
Esempio n. 16
0
        /// <summary>
        /// 接收表单数据处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="async">异步回调参数</param>
        private void onReceive(object sender, SocketAsyncEventArgs async)
#endif
        {
#if DOTNET2
            try
            {
                if (!async.CompletedSynchronously)
                {
                    Header.ReceiveTimeout.Cancel(httpSocket);
                }
                System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)async.AsyncState;
                if (socket == httpSocket.Socket)
                {
                    SocketError socketError;
                    int         count = socket.EndReceive(async, out socketError);
                    if (count > 0 && socketError == SocketError.Success)
                    {
                        receiveEndIndex += count;
                        contentLength   -= count;
                        if (onReceive())
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                httpSocket.DomainServer.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
            }
#else
            try
            {
                Header.ReceiveTimeout.Cancel(httpSocket);
                if (socketAsyncEventArgs.SocketError == SocketError.Success)
                {
                    int count = socketAsyncEventArgs.BytesTransferred;
                    if (count > 0)
                    {
                        receiveEndIndex += count;
                        contentLength   -= count;
                        if (onReceive())
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception error)
            {
                httpSocket.DomainServer.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
            }
#endif
            this.error();
        }
Esempio n. 17
0
        protected void EndReceive(System.IAsyncResult ar)
        {
            var buffer = ar.AsyncState as ReceiveBuffer;

            if (buffer == null)
            {
                //关闭连接
                Close();
                return;
            }
            //var socket = buffer.Tag as System.Net.Sockets.Socket;
            //if (socket == null)
            //    return -2;
            System.Net.Sockets.SocketError error;
            try
            {
                if (mSocket == null)
                {
                    return;
                }
                if (!mSocket.Connected)
                {
                    //关闭连接
                    Close();
                    return;
                }
                int result = mSocket.EndReceive(ar, out error);
                if (result < 1)
                {
                    //关闭连接
                    Close();
                    return;
                }
                buffer.count += result;
                unsafe
                {
                    fixed(byte *ptr = &buffer.buffer[0])
                    {
                        OnReceiveEventHandler((IntPtr)ptr, buffer.count);
                    }
                }
                //ReceiveBuffer buffer1 = new ReceiveBuffer();
                //mSocket.BeginReceive(buffer1.buffer, buffer1.count, buffer1.buffer.Length - buffer1.count, SocketFlags.None, EndReceive, buffer1);
                mRcvBuffer.Reset();
                mSocket.BeginReceive(mRcvBuffer.buffer, mRcvBuffer.count, mRcvBuffer.buffer.Length - mRcvBuffer.count, SocketFlags.None, EndReceive, mRcvBuffer);
                return;
            }
            catch (System.Exception ex)
            {
                Profiler.Log.WriteException(ex);
            }
            //关闭连接
            Close();
            return;
        }
Esempio n. 18
0
            public byte[] GetRecievedData(IAsyncResult ar)
            {
                int nBytesRec = 0;

                try{
                    nBytesRec = m_sock.EndReceive(ar);
                }
                catch { }
                byte[] byReturn = new byte[nBytesRec];
                Array.Copy(m_byBuff, byReturn, nBytesRec);
                return(byReturn);
            }
Esempio n. 19
0
        /// <summary>
        /// 数据接收完成的回调函数
        /// </summary>
        private void OnReceiveDataComplete(IAsyncResult ar)
        {
            _socket.EndReceive(ar);
            var data = ar.AsyncState as byte[];

            // 触发接收消息事件
            if (ReceiveMessageCompleted != null)
            {
                ReceiveMessageCompleted(this, new SocketEventArgs(data));
            }
            StartReceive();
        }
Esempio n. 20
0
	    public static async Task<bool> DiscoverAsync(object state = null)
	    {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 1900);

            byte[] outBuf = Encoding.ASCII.GetBytes(BroadcastPacket);
            byte[] inBuf = new byte[4096];

	        int tries = MaxTries;
	        while (--tries > 0)
	        {
	            try
	            {
	                TaskFactory factory = new TaskFactory();
	                sock.ReceiveTimeout = DiscoverTimeout;
	                await factory.FromAsync(sock.BeginSendTo(outBuf, 0, outBuf.Length, 0, endpoint, null, null), end =>
	                {
	                    sock.EndSendTo(end);
	                }).ConfigureAwait(false);
	                var ar = sock.BeginReceive(inBuf, 0, inBuf.Length, 0, null, null);
	                if (ar == null) throw new Exception("ar is null");
                    int length = await factory.FromAsync(ar, end => sock.EndReceive(end)).ConfigureAwait(false);

                    string data = Encoding.ASCII.GetString(inBuf, 0, length).ToLowerInvariant();

                    var match = ResponseLocation.Match(data);
                    if (match.Success && match.Groups["location"].Success)
                    {
                        System.Diagnostics.Debug.WriteLine("Found UPnP device at " + match.Groups["location"]);
                        string controlUrl = GetServiceUrl(match.Groups["location"].Value);
                        if (!string.IsNullOrEmpty(controlUrl))
                        {
                            _controlUrl = controlUrl;
                            System.Diagnostics.Debug.WriteLine("Found control URL at " + _controlUrl);
                            return true;                            
                        }
                    }

                }
	            catch (Exception ex)
	            {
	                // ignore timeout exceptions
	                if (!(ex is SocketException && ((SocketException) ex).ErrorCode == 10060))
	                {
	                    System.Diagnostics.Debug.WriteLine(ex.ToString());
	                }
	            }
	        }
            return false;
	    }
Esempio n. 21
0
        private void ClientTypeCallback(IAsyncResult value)
        {
            SocketConnection sc = null;

            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)value.AsyncState;
            int received = socket.EndReceive(value);

            byte[] dataBuf = new byte[received];
            Array.Copy(_buffer, dataBuf, received);
            string text = Encoding.ASCII.GetString(dataBuf);

            /*
             * //// PERMITE ONECCION WEBSOCKET
             * if (new Regex("^GET").IsMatch(text))
             * {
             *  WebSocketConnection wsc = new WebSocketConnection(socket, bufferSize);
             *  wsc.Disconnected += new SocketDisconnectedEventHandler(ClientDisconnected);
             *  wsc.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);
             *  wsc.WebSocketKey = new Regex("Sec-WebSocket-Key: (.*)").Match(text).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; // GUID;
             *
             *  wsc.Send(Encoding.ASCII.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
             + "Connection: Upgrade" + Environment.NewLine
             + "Upgrade: websocket" + Environment.NewLine
             + "Sec-WebSocket-Accept: " + Convert.ToBase64String(
             +          SHA1.Create().ComputeHash(
             +              Encoding.UTF8.GetBytes(wsc.WebSocketKey)
             +          )
             +      ) + Environment.NewLine
             + Environment.NewLine));
             +
             +  Connections.Add(wsc);
             +  OnAddClient(wsc);
             +  sc = wsc;
             + }
             + else
             + {*/
            sc = new SocketConnection(socket, bufferSize);
            sc.Disconnected += new SocketDisconnectedEventHandler(ClientDisconnected);
            sc.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);
            Connections.Add(sc);
            OnAddClient(sc);
            //}

            OnDataChange();

            sc.Listen();
        }
Esempio n. 22
0
        private void Readed(IAsyncResult ar)
        {
            if (!_Socket.Connected)
            {
                return;
            }

            var task = (Action <int>)ar.AsyncState;

            try
            {
                SocketError error;
                var         readCount = _Socket.EndReceive(ar, out error);
                task(readCount);
            }
            catch (Exception e)
            {
                _Enable = false;
            }
        }
Esempio n. 23
0
        void _instance_endReceive(IAsyncResult res)
        {
            Core.EventLoop.Instance.Push(() =>
            {
                int nRead   = nativeSocket.EndReceive(res);
                _bytesRead += nRead;

                if (OnData != null)
                {
                    Core.EventLoop.Instance.Push(() =>
                    {
                        byte[] data = new byte[nRead];
                        Array.Copy(_recv, data, nRead);

                        Core.EventLoop.Instance.Push(() =>
                        {
                            OnData(data);
                        });
                    });
                }
            });
        }
        /// <summary>
        /// AsyncReceivedCallback
        /// </summary>
        /// <param name="ar"></param>
        public void AsyncReceivedCallback(IAsyncResult ar)
        {
            SocketState state = (SocketState)ar.AsyncState;

            try
            {
                System.Net.Sockets.Socket client = state.workSocket;
                int bytesRead = client.EndReceive(ar);
                if (bytesRead > 0)
                {
                    Mark(string.Format("分析协议数据包"));
                    byte[] header_flag = new byte[2];
                    Array.Copy(state.buffer, 0, header_flag, 0, 2);
                    if (CommunicateProtocol.CheckFlag(header_flag))
                    {
                        client.BeginReceive(state.buffer, 0, 12, 0, new AsyncCallback(SyncExecuteProtocolCommand), state);
                    }
                    else
                    {
                        client.BeginReceive(state.buffer, 0, 2, 0, new AsyncCallback(AsyncReceivedCallback), state);
                    }
                }
                else
                {
                    WriteLog(null, "客户端" + IPAddress.Parse(((IPEndPoint)state.workSocket.RemoteEndPoint).Address.ToString()) + "连接异常");
                    SetConnection(false, state);
                }
            }
            catch (System.Net.Sockets.SocketException sktEx)
            {
                WriteLog(sktEx, sktEx.ErrorCode.ToString());
                SetConnection(false, state);
            }
            catch (Exception Ex)
            {
                WriteLog(Ex, Ex.Message);
                SetConnection(false, state);
            }
        }
Esempio n. 25
0
        private void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;

            System.Net.Sockets.Socket handler = state.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There  might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(
                                    state.buffer, 0, bytesRead));

                // Check for end-of-file tag. If it is not there, read
                // more data.
                content = state.sb.ToString();
                if (content.IndexOf("<EOF>") > -1)
                {
                    // All the data has been read from the
                    // client. Display it on the console.
                    Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                                      content.Length, content);
                    // Echo the data back to the client.
                    Send(handler, content);
                }
                else
                {
                    // Not all data received. Get more.
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                         new AsyncCallback(ReadCallback), state);
                }
            }
        }
        void ReceiveDataCallback(IAsyncResult asyncResult)
        {
            int receivedTextLength = -1;

            try {
                lock (this) {
                    receivedTextLength = socket.EndReceive(asyncResult);
                }
            } catch {
            }
            if (receivedTextLength <= 0)
            {
                Disconnect();
                return;
            }

            var receivedBuffer = (byte[])asyncResult.AsyncState;

            receivedBinaryStream.Write(receivedBuffer, 0, receivedTextLength);

            //// 末尾が '\0' かどうかチェック
            //receivedBinaryStream.Seek(0, System.IO.SeekOrigin.End);
            //if (receivedBinaryStream.ReadByte() == (int)'\0') {}

            // バイナリ -> テキスト変換
            var text = utf8.GetString(receivedBinaryStream.ToArray());

            receivedBinaryStream.Close();
            receivedBinaryStream = null;
            this.ReceiveTextEvent?.Invoke(this, new ReceiveTextEventArgs(text));
            receivedBinaryStream = new System.IO.MemoryStream();

            lock (this) {
                int offset = 0;
                // Async Recursive
                socket.BeginReceive(receivedBuffer, offset, receivedBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), receivedBuffer);
            }
        }
Esempio n. 27
0
        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                System.Net.Sockets.Socket client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                        new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    // All the data has arrived; put it in response.
                    if (state.sb.Length > 1)
                    {
                        _response = state.sb.ToString();
                    }

                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// SyncExecuteProtocolCommand
        /// </summary>
        /// <param name="ar"></param>
        public virtual void SyncExecuteProtocolCommand(IAsyncResult ar)
        {
            SocketState state = (SocketState)ar.AsyncState;

            try
            {
                System.Net.Sockets.Socket handler = state.workSocket;
                int bytesRead = handler.EndReceive(ar);

                Mark(string.Format("解析协议数据头"));

                if (bytesRead > 0)
                {
                    var protocol = ProtocolMgmt.InitProtocolHeader(state.buffer);

                    ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
                    {
                        Mark(string.Format("执行协议编号:{0}", protocol.Command));
                        InvokeExecuteProtocolCommand(protocol, state);
                    }));
                }
            }
            catch (System.Net.Sockets.SocketException SktEx)
            {
                WriteLog(SktEx, SktEx.ErrorCode.ToString());
                SetConnection(false, state);
            }
            catch (System.IO.IOException IoEx)
            {
                WriteLog(IoEx, IoEx.Message);
                SetConnection(false, state);
            }
            catch (Exception Ex)
            {
                WriteLog(Ex, Ex.Message);
                SetConnection(false, state);
            }
        }
Esempio n. 29
0
File: Client.cs Progetto: Gz1d/Gz
 /// <summary>
 /// 接收数据回调
 /// </summary>
 /// <param name="ia"></param>
 private void Receive(IAsyncResult ia)
 {
     try
     {
         client = ia.AsyncState as System.Net.Sockets.Socket;
         int count = client.EndReceive(ia);
         client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), client);
         string context = Encoding.UTF8.GetString(buf, 0, count);
         if (context.Length > 0)
         {
             //抛出事件
             if (this.OnSocketReceive != null)
             {
                 byte[] buf_tmp = new byte[count];
                 Array.Copy(buf, buf_tmp, count);
                 this.OnSocketReceive.BeginInvoke(this.DeviceType, client, buf_tmp, context, null, this.OnSocketReceive);
             }
         }
     }
     catch
     {
     }
 }
Esempio n. 30
0
 public void Run()
 {
     int len_receive_buf = 4096;
     int len_send_buf = 4096;
     byte[] receive_buf = new byte[len_receive_buf];
     byte[] send_buf=new byte[len_send_buf];
     int cout_receive_bytes;
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
     socket.Blocking = false;
     IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
     socket.Bind(new IPEndPoint(IPAddress.Parse(IPHost.AddressList[0].ToString()),5000));
     socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
     byte[] IN = new byte[4] { 1, 0, 0, 0 };
     byte[] OUT = new byte[4];
     int SIO_RCVALL = unchecked((int)0x98000001);
     int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT);
     while (true)
     {
         IAsyncResult ar = socket.BeginReceive(receive_buf, 0, len_receive_buf, SocketFlags.None, null, this);
         cout_receive_bytes = socket.EndReceive(ar);
         Receive(receive_buf, cout_receive_bytes);
     }
 }
        private void ReceiveCallback(IAsyncResult ar)
        {
            _current = (System.Net.Sockets.Socket)ar.AsyncState;
            int received;

            try
            {
                received = _current.EndReceive(ar);
            }
            catch (SocketException)
            {
                Console.WriteLine("Client forcefully disconnected");
                _current.Close();
                _clientSockets.Remove(_current);
                return;
            }

            var text = GenerateTextFromReceived(received);

            if (text.Contains("auth:"))
            {
                var newUser = text.Replace("auth:", string.Empty);
                var user    = new User(newUser, _current, _current.RemoteEndPoint.ToString());
                _users.Add(user);
                _store.Add(user.RemoteEndPoint, user);
                Console.WriteLine(newUser + " has joined the room.\n");
            }
            else
            {
                Send(text);
            }

            if (_current != null && (_current.Connected || !_current.Blocking))
            {
                _current.BeginReceive(_buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, _current);
            }
        }
Esempio n. 32
0
        private int _EndReceive(IAsyncResult arg)
        {
            SocketError error;
            int         size = Socket.EndReceive(arg, out error);

            if (size == 0)
            {
                _SocketErrorEvent(error);
            }

            if (!Socket.Connected)
            {
                _SocketErrorEvent(error);
                return(size);
            }

            if (error == SocketError.Success)
            {
                return(size);
            }

            _SocketErrorEvent(error);
            return(size);
        }
Esempio n. 33
0
        /// <summary>
        /// Processes incoming data from the socket.
        /// </summary>
        /// <param name="ar"></param>
        public void OnReceiveData(IAsyncResult ar)
        {
            _socket = (Socket)ar.AsyncState;

            try
            {
                int bytesReceived = _socket.EndReceive(ar);
                if (bytesReceived > 0)
                {
                    StringBuilder buffer = new StringBuilder();
                    for (int i = 0; i < bytesReceived; i++)
                    {
                        buffer.Append((Char)_inBuffer[i]);
                    }
                    _textCallback(buffer.ToString());
                    _inBuffer = null;
                    SetupReceiveCallback(_socket);
                }
            }
            catch
            {
                _textCallback("Error receiving data.");
                return;
            }
        }
Esempio n. 34
0
    private IEnumerator<ITask> Receive(Socket socketClient, NodeId nodeid) {
      if (socketClient == null) {
        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("SimpleFLM: Receive: socket == null!!!"));
        yield break;
      }

      if (!socketClient.Connected) {
        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("SimpleFLM: << {0} receive, but client is not connected", socketClient.RemoteEndPoint));
        HandleRemoteClosing(socketClient);
        yield break;
      }

      while (socketClient != null && m_ReloadConfig.State < ReloadConfig.RELOAD_State.Exit) {
        byte[] buffer = new byte[ReloadGlobals.MAX_PACKET_BUFFER_SIZE * ReloadGlobals.MAX_PACKETS_PER_RECEIVE_LOOP];

        var iarPort = new Port<IAsyncResult>();
        int bytesReceived = 0;

        try {
          m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET, String.Format("SimpleFLM: << {0} BeginReceive", socketClient == null ? "null" : socketClient.RemoteEndPoint.ToString()));
          socketClient.BeginReceive(
              buffer,
              0,
              buffer.Length,
              SocketFlags.None, iarPort.Post, null);
        }
        catch (Exception ex) {
          m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR, String.Format("SimpleFLM: << {0} BeginReceive", socketClient == null ? "null" : socketClient.RemoteEndPoint.ToString()) + ex.Message);
        }
        yield return Arbiter.Receive(false, iarPort, iar => {
          try {
            if (iar != null)
              bytesReceived = socketClient.EndReceive(iar);
          }
          catch (Exception ex) {
            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO,
              String.Format("SimpleFLM: << {0} Receive: {1} ",
              nodeid == null ? "" : nodeid.ToString(), ex.Message));
          }

          if (bytesReceived <= 0) {
            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET, 
              String.Format("SimpleFLM: << {0} Receive: lost connection, closing socket",
              socketClient.RemoteEndPoint));
            HandleRemoteClosing(socketClient);
            socketClient.Close();
            socketClient = null;
            return;
          }

          m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
            String.Format("SimpleFLM: << {0} Read {1} bytes from {2}",
            socketClient.RemoteEndPoint, 
            bytesReceived, nodeid == null ? "" : nodeid.ToString()));

          m_ReloadConfig.Statistics.BytesRx = (UInt64)bytesReceived;

#if CONNECTION_MANAGEMENT
          /* beginn connection management */
          long bytesProcessed = 0;
          SimpleOverlayConnectionTableElement socte = null;

          if (ReloadGlobals.Framing) {
            foreach (KeyValuePair<string, SimpleOverlayConnectionTableElement> pair in m_connection_table) {
              if (socketClient == pair.Value.AssociatedSocket) {
                socte = pair.Value;
                break;
              }
            }

            if (socte == null)
              socte = new SimpleOverlayConnectionTableElement();
            Array.Resize(ref buffer, bytesReceived);
            buffer = analyseFrameHeader(socte, buffer);
            bytesReceived = buffer.Length;
          }

          ReloadMessage reloadMsg = null;

          if (buffer != null) {
            reloadMsg = new ReloadMessage(m_ReloadConfig).FromBytes(buffer,
              ref bytesProcessed, ReloadMessage.ReadFlags.full);
          }

          if (socketClient != null && reloadMsg != null) {
            if (nodeid == null)
              nodeid = reloadMsg.LastHopNodeId;

            if (nodeid != null)
              if (m_connection_table.ContainsKey(nodeid.ToString())) {
                SimpleOverlayConnectionTableElement rcel = m_connection_table[
                  nodeid.ToString()];
                rcel.LastActivity = DateTime.Now;
              }
              else {
                SimpleOverlayConnectionTableElement rcel = socte;
                if (rcel == null)
                  rcel = new SimpleOverlayConnectionTableElement();
                rcel.NodeID = reloadMsg.LastHopNodeId;
                rcel.AssociatedSocket = socketClient;
                /*
                 * tricky: if this is an answer, this must be issued by an 
                 * outgoing request before (probably the first 
                 * bootstrap contact, where we have no nodeid from)
                 */
                rcel.Outbound = !reloadMsg.IsRequest();
                rcel.LastActivity = rcel.Start = DateTime.Now;

                m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
                  String.Format("SimpleFLM: << {0} Receive: Associating node {1}",
                  socketClient.RemoteEndPoint, rcel.NodeID.ToString()));
                lock (m_connection_table) {
                  if (nodeid != m_ReloadConfig.LocalNodeID) {
                    if (!m_connection_table.ContainsKey(rcel.NodeID.ToString()))
                      m_connection_table.Add(rcel.NodeID.ToString(), rcel);
                    else
                      m_connection_table[rcel.NodeID.ToString()] = rcel;
                  }
                }
              }
            /* end connection management */

            if (ReloadFLMEventHandler != null) {
              //there might by more then one packet inside
              m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
                String.Format("SimpleFLM: << {0} <== {1} {2}, TransID={3:x16}", socketClient.RemoteEndPoint, reloadMsg.reload_message_body.RELOAD_MsgCode.ToString(), nodeid.ToString(), reloadMsg.TransactionID));


              ReloadFLMEventHandler(this, new ReloadFLMEventArgs(
                ReloadFLMEventArgs.ReloadFLMEventTypes.RELOAD_EVENT_RECEIVE_OK,
                null, reloadMsg));

              if (bytesProcessed != bytesReceived) {
                long bytesProcessedTotal = 0;
                string lastMsgType = "";
                while (reloadMsg != null
                  && bytesProcessedTotal < bytesReceived) {
                  //in - offset out - bytesprocessed
                  bytesProcessed = bytesProcessedTotal;
                  //TKTODO add framing handling  here
                  reloadMsg = new ReloadMessage(m_ReloadConfig).FromBytes(
                    buffer, ref bytesProcessed, ReloadMessage.ReadFlags.full);
                  // Massive HACK!!! offset of TCP messages is set wrong TODO!!!
                  int offset = 0;
                  while (reloadMsg == null) {
                    offset++;
                    bytesProcessedTotal++;
                    bytesProcessed = bytesProcessedTotal;
                    reloadMsg = new ReloadMessage(m_ReloadConfig).FromBytes(
                      buffer, ref bytesProcessed, ReloadMessage.ReadFlags.full);
                    if (reloadMsg != null)
                      m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR,
                        String.Format("Last message type: {0}, offset: {1}",
                        lastMsgType, offset));
                  }
                  ReloadFLMEventHandler(this, new ReloadFLMEventArgs(
                    ReloadFLMEventArgs.ReloadFLMEventTypes.RELOAD_EVENT_RECEIVE_OK,
                    null, reloadMsg));
                  m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET,
                      String.Format("SimpleFLM: << {0} <== {1} {2}, TransID={3:x16}",
                      socketClient.RemoteEndPoint,
                      reloadMsg.reload_message_body.RELOAD_MsgCode.ToString(),
                      nodeid.ToString(),
                      reloadMsg.TransactionID));
                  bytesProcessedTotal += bytesProcessed;                  
                  lastMsgType = reloadMsg.reload_message_body.RELOAD_MsgCode.ToString();
                }
              }
            }
          }
          else {
            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR,
              String.Format("SimpleFLM: << {0} Receive: Dropping invalid packet,"+
              "bytes received: {1}", socketClient.RemoteEndPoint, bytesReceived));
          }
#endif
#if !CONNECTION_MANAGEMENT
                    m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_SOCKET, String.Format("SimpleFLM: << {0} Receive: Closing socket", client.RemoteEndPoint));
                    if(client.Connected)
                        client.Shutdown(SocketShutdown.Both);
                    client.Close();
#endif
        });
      }
    }
Esempio n. 35
0
		void HandleConnection(DateTime acceptedAt, Socket socket)
		{
			int bufferSize = 16384;
			var buffer = new byte[bufferSize];
			SocketError errorCode;
			socket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, out errorCode, asyncResult =>
				{
					try
					{
						int received = socket.EndReceive(asyncResult, out errorCode);
					}
					catch
					{
					}
					finally
					{
						socket.Close();

						ConnectionComplete();
					}
				}, this);

			// TODO create SocketConnection state machine as well, for connections created from the server
		}
Esempio n. 36
0
        public void HandleProcess(int p)
        {
            //trimite cerere de statistici si primeste raspuns pe un socket
            //lock, seteaza resetEvent-ul portului respectiv cand termina
            //lock , adauga statisticile in JobStatistics

            ProcessStatistics ps = null;
            // try
            // {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            System.Net.IPAddress ip = System.Net.IPAddress.Parse("127.0.0.1");
            System.Net.IPEndPoint remEP = new System.Net.IPEndPoint(ip, (Int32)p);
            sock.Connect(remEP);
            byte[] data = System.Text.Encoding.ASCII.GetBytes("2");
            sock.Send(data);
            byte[] recvData = new byte[4048];

            sock.BeginReceive(recvData, 0, recvData.Length, SocketFlags.None,
                              delegate(IAsyncResult res)
                              {
                                  int read = sock.EndReceive(res);

                                  String response = System.Text.Encoding.UTF8.GetString(recvData);
                                  string[] param1 = response.Split('_');
                                  int[] param = new int[param1.Count()];
                                  for (int i = 0; i < param1.Count(); i++)
                                  {
                                      param[i] = Int32.Parse(param1[i]);
                                  }
                                  ps = new ProcessStatistics(param[1], param[2], param[3], param[4], param[5]
                                      , param[6], param[7], param[8], param[9], DateTime.Now, DateTime.Now);

                                  lock (this._jobStatistics)
                                  {
                                      if (ps != null)
                                          this._jobStatistics.ProcessStatisticsList.Add(ps);
                                  }

                                  /*If all the sockets finished waiting, release the main thread.*/
                                  if (--this._waiting <= 0)
                                  {
                                      try
                                      {
                                          _event.Set();
                                      }
                                      catch (Exception ex)
                                      {

                                      }
                                  }

                              }, null);
            /*sock.ReceiveAsync(new SocketAsyncEventArgs()
                                  {

                                  });*/
            //}
            /*catch (Exception ex)
            {

                //;
            }*/
        }
Esempio n. 37
0
 private int socket_end_receiving_request(Socket socket, IAsyncResult asyncResult)
 {
     try
     {
         return socket.EndReceive(asyncResult);
     }
     catch (SocketException)
     {
         show_message("Error: Client was forcibly closed.");
         return 0;
     }
 }
        /// <summary>
        /// Startet die Anwendung. Dieses Besipiel liest eine TS Datei ein.
        /// </summary>
        /// <param name="args">Der Empfangsport und der Name der TS Datei.</param>
        public static void Main( string[] args )
        {
            // Be safe
            try
            {
                // Create socket to receive RTP stream
                using (var analyser = new RtpTransportStreamAnalyser())
                using (var file = new DoubleBufferedFile( args[1], 1000000 ))
                using (var socket = new Socket( AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp ) { Blocking = true })
                {
                    // Configure
                    socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 10000000 );

                    // Bind it
                    socket.Bind( new IPEndPoint( IPAddress.IPv6Any, ushort.Parse( args[0] ) ) );

                    // Buffer to use
                    var buffer = new byte[10000];

                    // First send to file
                    Action<byte[], int, int> sink = file.Write;

                    // Then to analyse
                    sink += analyser.Feed;

                    // Result processor
                    AsyncCallback whenDone = null;

                    // Starter
                    Action asyncRead = () => socket.BeginReceive( buffer, 0, buffer.Length, SocketFlags.None, whenDone, null );

                    // Define result processor
                    whenDone =
                        result =>
                        {
                            // Be safe
                            try
                            {
                                // Finish
                                var bytes = socket.EndReceive( result );

                                // Try to dispatch
                                RtpPacketDispatcher.DispatchTSPayload( buffer, 0, bytes, sink );

                                // Fire next
                                asyncRead();
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                        };

                    // Process
                    asyncRead();

                    // Wait for termination
                    Console.WriteLine( "Press ENTER to End" );
                    Console.ReadLine();

                    // Terminate connection
                    socket.Close();
                }
            }
            catch (Exception e)
            {
                // Report
                Console.WriteLine( "Error: {0}", e.Message );
            }

            // Done
            Console.ReadLine();
        }
Esempio n. 39
0
        /// <summary>
        /// Process data received from the socket.
        /// </summary>
        /// <param name="ar"></param>
        public void OnReceiveData( IAsyncResult ar )
        {
            _socket = (Socket) ar.AsyncState;

            if (_socket == null || !_socket.Connected)
                return;

            try
            {
                int bytesReceived = _socket.EndReceive(ar);
                if( bytesReceived > 0)
                {
                    string buffer = Encoding.ASCII.GetString(_inBuffer, 0, 1024);

                    AddTerminalText( buffer );
                    _inBuffer = null;
                }
                SetupReceiveCallback(_socket);
            }
            catch( SocketException ex)
            {
                MessageBox.Show("Error Receiving Data: " + ex.ToString());
                if (_socket != null)
                    _socket.Close();
                EnableConnect(true);
            }
            catch( Exception ex)
            {
                MessageBox.Show(ex.Message, "Error processing receive buffer!");
                return;
            }
        }
        public void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Fetch a user-defined object that contains information
                object[] obj = new object[2];
                obj = (object[])ar.AsyncState;
                // Received byte array
                byte[] buffer = (byte[])obj[0];
                // A Socket to handle remote host communication.
                handler = (Socket)obj[1];
                // Received message
                string content = string.Empty;
                // The number of bytes received.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    content += Encoding.Unicode.GetString(buffer, 0, bytesRead);

                    string[] mainSplit = content.Split(new Char[] { '&' });
                    string method = mainSplit[0];
                    string username = mainSplit[1];
                    string password = mainSplit[2];

                    #region Auth
                    if (method == "Auth")
                    {
                        GUI_Log("Auth request for: " + username + " , " + password);

                        if (isLoginValid(username, password))
                        {
                            //Send Auth Ok

                            GUI_Log("Auth OK for: " + username + " , " + password);
                            SendMessage("Auth_OK");
                        }
                        else
                        {
                            //Send Auth Failed
                            GUI_Log( "Auth Failed for User: "******"Auth_FAILED");
                        }
                    }
                    #endregion Auth

                    #region Register
                    if (method == "Register")
                    {
                        GUI_Log("Registration Request User: "******" & Password: "******"ok")
                        {
                            register_account(username, password);
                            GUI_Log("Registration for: " + username + " done!");
                            SendMessage("Register_OK");
                        }
                        else
                            if (isRegisterValid(username, password) == "failed")
                            {
                                //Send Reg Failed
                                GUI_Log("Registration failed: " + username);
                                SendMessage("Register_FAILED");
                            }
                            else
                                if (isRegisterValid(username, password) == "exist")
                                {
                                    GUI_Log("Account already exists: " + username);
                                    SendMessage("Register_EXIST");
                                }
                    }
                    #endregion Register

                    else
                    {
                        // Continues to asynchronously receive data
                        byte[] buffernew = new byte[1024];
                        obj[0] = buffernew;
                        obj[1] = handler;
                        handler.BeginReceive(buffernew, 0, buffernew.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), obj);
                    }
                }
            }
            catch (Exception)// ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Take the incoming data from a client and convert it into a TFMS_Data object
        /// </summary>
        /// <param name="socket">the socket that connects the server and the client</param>
        /// <param name="info">the information about the client from the socket</param>
        /// <param name="result">the result of the connection attempt</param>
        /// <returns></returns>
        private TFMS_Data extractData(Socket socket, TFMS_ClientInfo info, IAsyncResult result)
        {
            try
            {
                int numBytesReceived = socket.EndReceive(result); // EndReceive returns how many bytes were received
                byte[] temp = new byte[numBytesReceived];

                // the buffer might not be used for the first Received message so check if it exists
                // otherwise use the default buffer
                if (info == null || info.buffer == null)
                    Array.Copy(byteData, temp, numBytesReceived);
                else
                    Array.Copy(info.buffer, temp, numBytesReceived);

                // parse the bytes and turn it into a TFMS_Data object
                return new TFMS_Data(temp);
            }
            catch (SocketException)
            {
                // if something goes wrong, logoff the client
                return new TFMS_Data(TFMS_Command.Logout, null, getNamefromSocket(socket));
            }
        }
        private void receivePacketAndHandle(Socket clientSocket, IAsyncResult result)
        {
            int packetLen = clientSocket.EndReceive(result);
            byte[] packet = new byte[packetLen];
            Buffer.BlockCopy(buffer, 0, packet, 0, packetLen);

            handler.Handle(packet);
        }
Esempio n. 43
0
        /// <summary>
        /// 接收客户端信息
        /// </summary>
        /// <param name="client"></param>
        public void RecieveAsync(Socket client) {
            byte[] bytes = new byte[5*1024*1024];
            client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, ac => {
                try {

                    int read = client.EndReceive(ac);
                    if (read == 0) {
                        //客户端已关闭
                        RemoveClientAction(client);
                    }
                    else { 
                        string message = System.Text.Encoding.UTF8.GetString(bytes, 0, read);
                        RecieveAction(client, message);
                        RecieveAsync(client);
                    }
                }
                catch (Exception ex) {
                    ExceptionAction(ex, client);
                }

            }, null);
        }
Esempio n. 44
0
        private void BeginReceive(IAsyncResult iar)
        {
            try
            {
                if (isConnected())
                {
                    client = (Socket)iar.AsyncState;

                    int bytesRead = client.EndReceive(iar);

                    if (bytesRead != 0)
                    {
                        string message = Encoding.ASCII.GetString(data, 0, bytesRead);

                        msgReceived(this, new MessageReceivedEventArgs(message));
                    }

                    client.BeginReceive(data, 0, 2048, SocketFlags.None, new AsyncCallback(BeginReceive), client);
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine(String.Format("{0} {1}", ex.Message, ex.ErrorCode));

                if (receiveFailed != null)
                    receiveFailed(this, new EventArgs());
            }
        }
Esempio n. 45
0
        private void ConnectToHub(IPEndPoint printerHubEndpoint)
        {
            Ensure.NotNull(printerHubEndpoint, nameof(printerHubEndpoint));

            _printerHubSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _printerHubSocket.Connect(printerHubEndpoint);

            byte[] messageLength = new byte[2];
            int receiveCount = 0;

            AsyncCallback receiveCallback = null;
            receiveCallback = (receiveResult) =>
            {
                try
                {
                    receiveCount += _printerHubSocket.EndReceive(receiveResult);
                    if (receiveCount != 2)
                    {
                        _printerHubSocket.BeginReceive(messageLength, receiveCount, messageLength.Length, SocketFlags.None, receiveCallback, null);
                        return;
                    }

                    int length = (messageLength[0] << 8) + messageLength[1];
                    if (length < 1 || length > 65280)
                        throw new Exception($"Invalid message length received [{length}]");

                    byte[] data = new byte[length];

                    int readCount = 0;
                    while (readCount < data.Length)
                    {
                        _printerHubSocket.ReceiveTimeout = 2000;

                        int count = _printerHubSocket.Receive(data, readCount, data.Length - readCount, SocketFlags.None);
                        if (count == 0)
                            throw new Exception("Socket closed on read operation");

                        readCount += count;
                    }

                    if (readCount != length)
                        throw new Exception("Cannot receive full message");

                    try
                    {
                        Process(data);
                    }
                    catch (Exception ex)
                    {
                        _context.Log.LogError(ex);
                    }

                    _printerHubSocket.BeginReceive(messageLength, receiveCount = 0, messageLength.Length, SocketFlags.None, receiveCallback, null);
                }
                catch (Exception ex)
                {
                    _context.Log.LogError(ex);

                    try
                    {
                        _printerHubSocket.Shutdown(SocketShutdown.Both);
                        _printerHubSocket.Close();
                    }
                    catch { }
                }
            };

            _printerHubSocket.BeginReceive(messageLength, 0, messageLength.Length, SocketFlags.None, receiveCallback, null);

            Request request = new Request
            {
                PrinterId = _printerId,
                RequestId = Guid.NewGuid().ToString(),
                RequestType = "Initialization",
                Content = JsonConverter.Serialize(new Initialize())
            };

            _printerHubSocket.Send(Network.CreatePacket(JsonConverter.Serialize(request)));
        }
Esempio n. 46
0
 protected void WaitForCommand(Socket socket, CommandReceivedEventHandler callback, byte[] commandBuffer, int commandBufferSize = 1024)
 {
     if (commandBuffer == null)
     {
         commandBuffer = new byte[commandBufferSize];
     }
     try
     {
         socket.BeginReceive(commandBuffer, 0, commandBufferSize, 0,
                                 asyncResult =>
                                 {
                                     int bytesRead;
                                     try
                                     {
                                         bytesRead = socket.EndReceive(asyncResult);                                                
                                     }
                                     catch (Exception exception)
                                     {
                                         if (OnErrorOcurred != null)
                                         {
                                             OnErrorOcurred(exception);
                                         }
                                         if (OnSocketDisconnected != null)
                                         {
                                             OnSocketDisconnected(socket);
                                         }
                                         return;
                                     }
                                     if (bytesRead <= 0)
                                     {
                                         if (OnSocketDisconnected != null)
                                         {
                                             OnSocketDisconnected(socket);
                                         }
                                         return;
                                     }
                                     var command = DongleEncoding.Default.GetString(commandBuffer, 0, bytesRead);
                                     if (callback != null)
                                     {
                                         try
                                         {
                                             callback(command);
                                         }
                                         catch (ThreadAbortException)
                                         {
                                             //Treadh abortada. Nada a fazer
                                         }
                                         catch (Exception exception)
                                         {
                                             if (OnErrorOcurred != null)
                                             {
                                                 OnErrorOcurred(exception);
                                             }
                                             else
                                             {
                                                 throw;
                                             }
                                         }                                                
                                     }
                                 },
                              null);
     }
     catch (Exception)
     {
         if (OnSocketDisconnected != null)
         {
             OnSocketDisconnected(socket);
         }
     }
     
 }
Esempio n. 47
0
 private void RunReceiver()
 {
     try
     {
         try
         {
             ipSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
             try
             {
                 ipSocket.Bind(endp);
                 ipSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                 ipSocket.IOControl(unchecked((int)0x98000001), new byte[4] { 1, 0, 0, 0 }, new byte[4]);
                 while (stopButton.Enabled)
                 {
                     IAsyncResult ar = ipSocket.BeginReceive(PacketBuffer, 0, PacketBufferSize, SocketFlags.None, new AsyncCallback(CallReceive), this);
                     while (ipSocket.Available == 0)
                     {
                         Thread.Sleep(1);
                         if (!stopButton.Enabled) break;
                     }
                     Thread.Sleep(1);
                     if (!stopButton.Enabled) break;
                     int Size = ipSocket.EndReceive(ar);
                     if (!looseQueue.Checked) ExtractBuffer();
                 }
             }
             finally
             {
                 if (ipSocket != null)
                 {
                     ipSocket.Shutdown(SocketShutdown.Both);
                     ipSocket.Close();
                 }
             }
         }
         finally
         {
             Button e = stopButton;
             if (e.InvokeRequired)
             {
                 e.BeginInvoke((MethodInvoker)delegate
                 {
                     stopButton.Enabled = false;
                 });
             }
             else
             {
                 stopButton.Enabled = false;
             }
             Button f = startButton;
             if (f.InvokeRequired)
             {
                 f.BeginInvoke((MethodInvoker)delegate
                 {
                     startButton.Enabled = true;
                 });
             }
             else
             {
                 startButton.Enabled = true;
             }
         }
     }
     catch (ThreadAbortException)
     {
     }
     catch (Exception E)
     {
         MessageBox.Show(E.ToString());
     }
     Button g = startButton;
     if (g.InvokeRequired)
     {
         g.BeginInvoke((MethodInvoker)delegate
         {
             startButton.Enabled = true;
         });
     }
     else
     {
         startButton.Enabled = true;
     }
 }
Esempio n. 48
0
		void ReceiveFromConnection(Socket connection)
		{
			DateTime acceptedAt = SystemUtil.UtcNow;

			var buffer = new byte[ReceiveMessageSize];
			SocketError errorCode;

			AsyncCallback receiver = null;
			receiver = ar =>
				{
					bool close = false;

					try
					{
						if (_disposed)
							return;

						int length = connection.EndReceive(ar);
						if (length == 0)
						{
							close = true;
							return;
						}

						_output.Send(new ArraySegment<byte>(buffer, 0, length));
					}
					catch (ObjectDisposedException)
					{
					}
					catch (Exception ex)
					{
						Console.WriteLine("Wow: " + ex);
					}
					finally
					{
						if (_disposed || close)
							connection.CloseAndDispose();
						else
							connection.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, out errorCode, receiver, null);
					}
				};

			connection.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, out errorCode, receiver, null);
		}
Esempio n. 49
0
        public void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Fetch a user-defined object that contains information
                object[] obj = new object[2];
                obj = (object[])ar.AsyncState;

                // Received byte array
                byte[] buffer = (byte[])obj[0];

                // A Socket to handle remote host communication.
                handler = (Socket)obj[1];

                // Received message
                string content = string.Empty;

                // The number of bytes received.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    content += Encoding.Unicode.GetString(buffer, 0,
                        bytesRead);

                        // Continues to asynchronously receive data
                        byte[] buffernew = new byte[1024];
                        obj[0] = buffernew;
                        obj[1] = handler;
                        handler.BeginReceive(buffernew, 0, buffernew.Length,
                            SocketFlags.None,
                            new AsyncCallback(ReceiveCallback), obj);

                    /*
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
                    {
                        tbAux.Text = content;
                    }
                    );*/
                }
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
Esempio n. 50
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                _clientSocket = (Socket)ar.AsyncState;
                int rLen = _clientSocket.EndReceive(ar);

                if (rLen > 0)
                {
                    foreach (var packet in PacketReceiver.GetPackets(_receivedBytes.Take(rLen).ToArray(), _clientSocket.ReceiveBufferSize))
                    {
                        IncomingMessageCount++;
                        InvokeConnectionClientEvent(new ConnectionClientEventArgs(ConnectionClientEventType.MESSAGE_RECEIVED, packet));
                    }
                    _receivedBytes = new byte[_clientSocket.ReceiveBufferSize];
                    _clientSocket.BeginReceive(_receivedBytes, 0, _receivedBytes.Length, SocketFlags.None, new AsyncCallback(OnReceive), _clientSocket);
                }
            }
            catch (ObjectDisposedException oex)
            {
                InvokeConnectionClientEvent(new ConnectionClientEventArgs(ConnectionClientEventType.ERROR_OCCURED, "Error during connection  (OnReceive, Disposed): " + oex.Message));
            }
            catch (Exception ex)
            {
                InvokeConnectionClientEvent(new ConnectionClientEventArgs(ConnectionClientEventType.ERROR_OCCURED, "Connection lost -> " + ex.Message));
                ResetSocket(_reconnect);
            }
        }
Esempio n. 51
0
        protected void WaitForFile(Socket socket, FileReceivedEventHandler fileReceivedCallback, int fileSize, int bufferSize = DefaultBufferSize, byte[] previousPart = null, int currentPart = 0, int totalParts = 1)
        {
            if (currentPart == 0)
            {
                totalParts = (int)Math.Ceiling(Convert.ToDouble(fileSize) / Convert.ToDouble(bufferSize));
            }
            var buffer = new byte[bufferSize];            
            try
            {
                SocketError errorCode;
                socket.BeginReceive(buffer, 0, bufferSize, 0, out errorCode, asyncResult =>
                {
                    byte[] newPart;
                    Debug.WriteLine("RECEIVING FILE " + currentPart + "/" + totalParts);
                    var bufferRealSize = buffer.Length;
                    if(fileSize <= bufferSize)
                    {
                        bufferRealSize = fileSize;
                    }                    
                    else if(currentPart == totalParts - 1)
                    {
                        bufferRealSize = fileSize - (currentPart*bufferSize);
                    }
                    Array.Resize(ref buffer, bufferRealSize);

                    if (buffer.Length == 0 && previousPart == null)
                    {
                        newPart = null;
                    }
                    else if (buffer.Length == 0 && previousPart != null)
                    {
                        newPart = previousPart;
                    }
                    else if (previousPart != null)
                    {
                        var newPartLength = previousPart.Length + buffer.Length;
                        var bufferLength = buffer.Length;
                        if (newPartLength > fileSize)
                        {
                            newPartLength = fileSize;
                            bufferLength = fileSize - previousPart.Length;
                        }
                        newPart = new byte[newPartLength];
                        Buffer.BlockCopy(previousPart, 0, newPart, 0,
                                         previousPart.Length);
                        Buffer.BlockCopy(buffer, 0, newPart, previousPart.Length,
                                         bufferLength);
                    }
                    else
                    {
                        newPart = buffer;
                    }

                    if (newPart == null || newPart.Length < fileSize)
                    {
                        WaitForFile(socket, fileReceivedCallback, fileSize, bufferSize, newPart, currentPart + 1, totalParts);
                        return;
                    }

                    try
                    {
                        socket.EndReceive(asyncResult);
                    }
                    catch (Exception exception)
                    {
                        if (OnErrorOcurred != null)
                        {
                            OnErrorOcurred(exception);
                        }
                        if (OnSocketDisconnected != null)
                        {
                            OnSocketDisconnected(socket);
                        }
                        return;
                    }

                    if (fileReceivedCallback != null)
                    {
                        fileReceivedCallback(newPart);
                    }
                }, null);
            }
            catch (Exception exception)
            {
                if (OnErrorOcurred != null)
                {
                    OnErrorOcurred(exception);
                }
                if (OnSocketDisconnected != null)
                {
                    OnSocketDisconnected(socket);
                }
            }
            
        }
Esempio n. 52
0
        private void NetworkReceive(SocketPurpose Purpose, Socket NetworkSocket, IAsyncResult ar)
        {
            try
            {
                int length = NetworkSocket.EndReceive(ar);
                if (length > 0)
                {
                    ProcessData Processor = null;

                    if (Purpose == SocketPurpose.Debug)
                        Processor = debugProcessor.Process;
                    else if (Purpose == SocketPurpose.Control)
                        Processor = controlProcessor.Process;

                    if (Processor != null)
                    {
                        Processor.BeginInvoke(networkBuf, length,
                            delegate(IAsyncResult AsR) { ProcessFinish(Processor, Purpose, NetworkSocket, AsR); },
                            null);
                    }
                    else
                    {
                        throw new Exception("In network receive with invalid purpose, this should not happen");
                    }

                }
                else
                {
                    Console.WriteLine("{0} connection closed", SocketName(Purpose));

                    DeviceInUse = false;
                    StartListen();
                }
            }
            catch (SocketException e)
            {
                OnSocketException(Purpose, NetworkSocket, e);
            }
            catch (ObjectDisposedException)
            {
                OnObjectDisposedException(Purpose, NetworkSocket);
            }
        }
Esempio n. 53
0
        public void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Fetch a user-defined object that contains information 
                object[] obj = new object[2];
                obj = (object[])ar.AsyncState;

                // Received byte array 
                byte[] buffer = (byte[])obj[0];

                // A Socket to handle remote host communication. 
                handler = (Socket)obj[1];

                // Received message 
                string content = string.Empty;


                // The number of bytes received. 
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    content += Encoding.Unicode.GetString(buffer, 0,
                        bytesRead);

                    // If message contains "<Client Quit>", finish receiving
                    if (content.IndexOf("<Client Quit>") > -1)
                    {
                        // Convert byte array to string
                        string str = content.Substring(0, content.LastIndexOf("<Client Quit>"));

                        //this is used because the UI couldn't be accessed from an external Thread
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
                        {
                            tbAux.Text = "Read " + str.Length * 2 + " bytes from client.\n Data: " + str;
                        }
                        );
                    }
                    else
                    {
                        // Continues to asynchronously receive data
                        byte[] buffernew = new byte[1024];
                        obj[0] = buffernew;
                        obj[1] = handler;
                        handler.BeginReceive(buffernew, 0, buffernew.Length,
                            SocketFlags.None,
                            new AsyncCallback(ReceiveCallback), obj);
                    }

                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
                    {
                        tbAux.Text = content;
                    }
                    );
                }
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
Esempio n. 54
0
 public override void Receive(System.Action<string,Socket> ReceiveAction, Socket Source)
 {
     Byte[] msg = new byte[65535];
     //异步的接受消息
     Source.BeginReceive(msg, 0, msg.Length, SocketFlags.None,
             ar =>
             {
                 //对方断开连接时, 这里抛出Socket Exception
                 //An existing connection was forcibly closed by the remote host
                 try
                 {
                     Source.EndReceive(ar);
                     ReceiveAction(Encoding.UTF8.GetString(msg).Trim('\0', ' '), Source);
                     Receive(ReceiveAction, Source);
                 }
                 catch (Exception e)
                 {
                     if (e is SocketException)
                     {
                         NumberToShutdown = communicateSockets.IndexOf(Source);
                     }
                 }
             }, null);
 }
Esempio n. 55
0
        /* This method is executed after AcceptCallBack for receiving and manipulating the
         * incoming data from the client.
         */
        public void ReceiveCallback(IAsyncResult ar)
        {
            //The code is written in try block so as to catch any exceptions, if thrown
            try
            {

                // Fetch a user-defined object that contains information
                object[] obj = new object[2];
                obj = (object[])ar.AsyncState;
                // Received byte array
                byte[] buffer = (byte[])obj[0];
                // A Socket to handle remote host communication
                handler = (Socket)obj[1];
                // string content is first made empty
                string content = string.Empty;
                // The number of bytes received.
                int bytesRead = handler.EndReceive(ar);

                // If there is atleast one character in the message, then begin manipulating it
                if (bytesRead > 0)
                {
                    // Content is filled with data from buffer after encoding it
                    content += Encoding.Unicode.GetString(buffer, 0, bytesRead);

                    // Convert byte array to string untill the End Of File <Client Quit> is reached
                    string str = content.Substring(0, content.LastIndexOf("<Client Quit>"));

                    // Start a loop, which will iterate 8 times, as there are 8 words in thesaurus
                    for (i = 0; i < 8;)
                    {
                        // Checking if the received word is in the test data of thesaurus
                        if (str == word[i])
                        {
                            // If a match is found, the string with alternate words of the
                            // given word is copied in alternate variable, and the loop is exited.
                            alternate = alt [i];
                            break;
                        }
                        else
                        {
                            // If a match is not found, alternate variable is made empty and
                            // the loop counter is incremented by 1.
                            alternate = "";
                            i++;
                        }
                    }
                    // If the alternate variable is empty after checking all the words in the
                    // dictionary, it is filled with string "Not in Dictionary!" for indicating
                    // the same to the user.
                    if(alternate == "")
                    {
                           alternate = "Not in Dictionary!";
                    }

                    // Prepare the reply message
                    byte[] altreply =  Encoding.Unicode.GetBytes(alternate);

                    // Sends the string of alternate words asynchronously to the client
                    handler.BeginSend(altreply, 0, altreply.Length, 0, new AsyncCallback(SendCallback), handler);

                    // Continues to asynchronously receive data
                    byte[] buffernew = new byte[1024];
                    obj[0] = buffernew;
                    obj[1] = handler;
                    handler.BeginReceive(buffernew, 0, buffernew.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), obj);
                }
            }
            // Used for catching any exceptions, if thrown
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
Esempio n. 56
0
        public void ReceiveCallback(IAsyncResult ar)
        {
            // Fetch a user-defined object that contains information 
            object[] obj = new object[2];
            obj = (object[])ar.AsyncState;

            // Received byte array 
            byte[] buffer = (byte[])obj[0];

            // A Socket to handle remote host communication. 
            handler = (Socket)obj[1];

            // The number of bytes received. 
            int bytesRead = handler.EndReceive(ar);



            string[] res = Protocol.reciveProtocol(ar, handler, buffer, flag, bytesRead);


            if(res[2] == "file")
            {                
                string content = res[1];
                //var upd = content.Substring(5);
                
                int flag2 = myFiles.reciveFile(ar, flag, handler, buffer, bytesRead);
                if (flag2 >= 1)
                {
                    handler.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReceiveCallback), obj);
                }






				// UPD valido
				if (true)
				{


					// FIXME aggiornamenti database



					Protocol.response("+UPG\r\n");
                }
				else
				{
					//errore = true;
				}
			}
        


            if (res[0] == "true")
            {
                //response("-ERR\r\n");

                // Prepare the reply message 
                byte[] byteData = Encoding.Unicode.GetBytes("-ERR\r\n");

                // Sends data asynchronously to a connected Socket 
                handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(socket_server.SendCallback), handler);
            }
            else
            {
                //Continues to asynchronously receive data
                byte[] buffernew = new byte[1024];
                obj[0] = buffernew;
                obj[1] = handler;
                handler.BeginReceive(buffernew, 0, buffernew.Length,
                        SocketFlags.None, new AsyncCallback(ReceiveCallback), obj);
            }

            //this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            //{
            //    tbAux.Text = res[1];
            //}
            //);

        }
Esempio n. 57
0
 int Utils.Wrappers.Interfaces.ISocket.EndReceive(System.IAsyncResult asyncResult)
 {
     return(InternalSocket.EndReceive(asyncResult));
 }
Esempio n. 58
0
        public void Run()
        {
            //we will set the I/O buffer lengths at 4096 bytes - plenty big enough for a 802.3 packet
            int len_receive_buf = 4096;
            int len_send_buf = 4096;

            byte[] receive_buf = new byte[len_receive_buf];
            byte[] send_buf = new byte[len_send_buf];
            int cout_receive_bytes;

            /*Create a socket - the Socket class allows us to set many options for the socket

            The AddressFamily property specifies the addressing scheme that an instance of the Socket
            class can use.  This property is read-only and is set when the Socket is created.
            In C#, AddressFamily is an enumeration; each value it can take corresponds to some integer
            The InterNetwork value represents IPv4.

            A raw socket supports access to the underlying transport protocol. Using the SocketType Raw,
            you can communicate using protocols like Internet Control Message Protocol (Icmp).
            Your application must provide a complete IP header when sending. Received datagrams return
            with the IP header and options intact.
            Note: SocketType is also an enumeration and Raw is one of its values

            ProtocolType is another enumeration; the IP value sets the protocol to IP

            */
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

            /*If you are in blocking mode, and you make a method call which does not complete immediately,
            your application will block execution until the requested operation completes.*/
            socket.Blocking = false;

            //Get the IPAddress address list of the local host
            IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());

            //Bind the socket to the first IP address returned above
            socket.Bind(new IPEndPoint(IPAddress.Parse(IPHost.AddressList[0].ToString()), 0));

            //Set the socket options - IP means Socket options apply only to IP sockets
            //SocketOptionName.HeaderIncluded-Indicates that the application provides the IP header
            //for outgoing datagrams.
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);

            //The following mods change the socket so that it can receive all IP packets on the network
            byte[] IN = new byte[4] { 1, 0, 0, 0 };
            byte[] OUT = new byte[4];
            int SIO_RCVALL = unchecked((int)0x98000001);

            //IOControl(Int32, Byte[], Byte[]) - Sets low-level operating modes for the Socket
            //using numerical control codes.
            //For more information look up the Windows WSAIoctl function
            int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT);
            while (true)
            {
                /*BeginReceive(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object)
                Begins to asynchronously receive data from a connected Socket.
                Parameters:
                buffer-An array of type Byte that is the storage location for the received data.
                offset-The zero-based position in the buffer parameter at which to store the received data.
                size-The number of bytes to receive.
                socketFlags-A bitwise combination of the SocketFlags values.
                callback-An AsyncCallback delegate that references the method to invoke when the operation is complete.
                state-A user-defined object that contains information about the receive operation.
                    This object is passed to the EndReceive delegate when the operation is complete.
                Return Value: An IAsyncResult that references the asynchronous read.*/
                IAsyncResult ar = socket.BeginReceive(receive_buf, 0, len_receive_buf, SocketFlags.None, null, this);

                //EndReceive raps up the read, and returns an array of bytes
                cout_receive_bytes = socket.EndReceive(ar);
                //output the packet (to the listbox on the form)
                ProcessPacket(receive_buf, cout_receive_bytes);
            }
        }
Esempio n. 59
0
        /// <summary>
        /// 数据接收完成后的处理
        /// </summary>
        /// <returns></returns>
        private bool onReceive()
#endif
        {
#if DOTNET2
            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)async.AsyncState;
            if (socket == Socket)
            {
                SocketError socketError;
                int count = socket.EndReceive(async, out socketError);
                if (socketError == SocketError.Success)
                {
#else
        START:
            if (receiveAsyncEventArgs.SocketError == SocketError.Success)
            {
                int count = receiveAsyncEventArgs.BytesTransferred;
#endif
                    Data.MoveStart(count);
                    if (Data.Length == 0)
                    {
                        ReceiveSizeLessCount = 0;
                        switch (ReceiveType)
                        {
                            case ReceiveType.Response:
                                if ((Header.ContentLength -= Buffer.Length) <= 0) return responseHeader();
                                Data.Set(Buffer.Buffer, Buffer.StartIndex, Math.Min(Header.ContentLength, Buffer.Length));
#if DOTNET2
                                if (socket == Socket)
                                {
                                    async = socket.BeginReceive(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onReceiveAsyncCallback, socket);
                                    if (socketError == SocketError.Success)
                                    {
                                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                        return true;
                                    }
                                }
                                return false;
#else
                            System.Net.Sockets.Socket socket = Socket;
                            if (socket == null) return false;
                            ReceiveAsyncLock.EnterSleepFlag();
                            receiveAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                            if (socket.ReceiveAsync(receiveAsyncEventArgs))
                            {
                                ReceiveAsyncLock.SleepFlag = 0;
                                Http.Header.ReceiveTimeout.Push(this, socket);
                                ReceiveAsyncLock.Exit();
                                return true;
                            }
                            ReceiveAsyncLock.ExitSleepFlag();
                            goto START;
#endif
                            case ReceiveType.GetForm: return OnGetForm();
                        }
                    }
                    if ((count >= TcpServer.Server.MinSocketSize || (count > 0 && ReceiveSizeLessCount++ == 0)) && AutoCSer.Threading.SecondTimer.Now <= Timeout)
                    {
#if DOTNET2
                        if (socket == Socket)
                        {
                            async = socket.BeginReceive(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onReceiveAsyncCallback, socket);
                            if (socketError == SocketError.Success)
                            {
                                if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                return true;
                            }
                        }
#else
                    System.Net.Sockets.Socket socket = Socket;
                    if (socket == null) return false;
                    ReceiveAsyncLock.EnterSleepFlag();
                    receiveAsyncEventArgs.SetBuffer(Data.Start, Data.Length);
                    if (socket.ReceiveAsync(receiveAsyncEventArgs))
                    {
                        ReceiveAsyncLock.SleepFlag = 0;
                        Http.Header.ReceiveTimeout.Push(this, socket);
                        ReceiveAsyncLock.Exit();
                        return true;
                    }
                    ReceiveAsyncLock.ExitSleepFlag();
                    goto START;
#endif
                }
#if DOTNET2
                }
#endif
            }
            return false;
        }
Esempio n. 60
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            clientSocket = (Socket)ar.AsyncState;

            // read data from client as much as specified ReceivedBufferObject allowed
            int readPacketData = clientSocket.EndReceive(ar);

            // if 0 bytes were read, client shutdown socket, and all available data has been received.
            if (readPacketData > 0)
            {
                // convert data to string and store in the state object
                string message = Encoding.ASCII.GetString(buffer, 0, readPacketData);
                data += message;

                try
                {
                    // if the end of the data was found, we're done
                    if (message.IndexOf('\n') > -1)
                    {
                        // tell listening application that server is communicating with it
                        ReceiveToApplication(new ServerToApplicationEvent(data));

                        // ask for more messages
                        data = "";
                        clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
                    }
                    // otherwise, retrieve more data
                    else
                    {
                        Console.WriteLine("Server sent partial message.");
                        clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
                    }
                }
                catch (Exception e )
                {
                    Console.WriteLine("Server closed socket:" + e.ToString());
                    Shutdown();
                }
            }
            else
            {
                Console.WriteLine("Warning: 0 packet sent from server.");
            }
        }