BeginReceive() public method

public BeginReceive ( IList buffers, SocketFlags socketFlags, AsyncCallback callback, object state ) : IAsyncResult
buffers IList
socketFlags SocketFlags
callback AsyncCallback
state object
return IAsyncResult
Esempio n. 1
0
    private void OnConnect(IAsyncResult ar)
    {
        try {
            clientSocket.EndConnect(ar);
            // here we are connected, so we send login request!
            byte[]  bytesMsg;
            Message loginMsg = new Message(Command.Login, txtName.Text);
            bytesMsg = loginMsg.toByte();

            clientSocket.BeginSend(bytesMsg,
                                   0,
                                   bytesMsg.Length,
                                   SocketFlags.None,
                                   new AsyncCallback(OnSend),
                                   null);
            clientSocket.BeginReceive(byteData,
                                      0,
                                      byteData.Length,
                                      SocketFlags.None,
                                      new AsyncCallback(OnReceive),
                                      null);
        }
        catch (Exception ex) {
            log("Something went wrong during establishing connection:");
            log(ex.Message);
            btnConnect.Sensitive    = true;
            btnDisconnect.Sensitive = false;
            btnMsg.Sensitive        = false;
        }
    }
 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. 3
0
        /// <summary>
        /// 开始接收消息
        /// </summary>
        private void StartReceive()
        {
            if (!_socket.Connected)
            {
                return;
            }
            var buffer = new byte[_decoderLengthFieldLength];

            _socket.BeginReceive(buffer, 0, _decoderLengthFieldLength, SocketFlags.None, OnReceiveFrameLengthComplete, buffer);
        }
Esempio n. 4
0
 public Server(Socket _Sock)
 {
     Sock = _Sock;
     Sock.BeginReceive(Buffer, 0, 8192, SocketFlags.None, new AsyncCallback(WaitForData), Sock);
     ScSec = new PacketSecurity(true);
     CsSec = new PacketSecurity(false);
 }
Esempio n. 5
0
        public Program(string outputfilename)
        {
            try
            {
                _output = File.Open(outputfilename, FileMode.Create);

                System.Console.WriteLine("Capturing output to: " + _output.Name);
            }
            catch (IOException e)
            {
                Abort(e);
            }

            try
            {
                IPHostEntry e = Dns.GetHostEntry(HOST);

                _incoming = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                System.Console.WriteLine("Resolved {0} to {1}.", HOST, e.AddressList[0].ToString());

                _incoming.Connect(e.AddressList, PORT);

                _incoming.ReceiveTimeout = 10000; // 10 seconds because we may not always be receiving data

                _incoming.BeginReceive(_blob, 0, BLOB_SIZE, SocketFlags.None, new AsyncCallback(OnReceiveData), null);
            }
            catch (SocketException e)
            {
                Abort(e);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// AsyncConnectCallback
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncConnectCallback(IAsyncResult ar)
        {
            SocketState state = new SocketState();

            try
            {
                System.Net.Sockets.Socket handler = (System.Net.Sockets.Socket)ar.AsyncState;
                handler.EndConnect(ar);
                state            = new SocketState();
                state.workSocket = handler;
                //handler.SendTimeout = SendTimeOutMS;
                //handler.ReceiveTimeout = ReceiveTimeOutMS;

                Mark(string.Format("连接成功"));
                state.IsReceiveThreadAlive = true;
                statelst.Add(state);
                SetConnection(true, state);
                handler.BeginReceive(state.buffer, 0, 2, 0, new AsyncCallback(AsyncReceivedCallback), 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);
            }
            finally
            {
                connectDone.Set();
            }
        }
Esempio n. 7
0
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if ((sender as CheckBox).Checked)
            {
                (sender as CheckBox).Text = "&Stop me";
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                try
                {
                    socket.Bind(new IPEndPoint(IPAddress.Parse(comboBox1.SelectedItem.ToString()), 0));
                    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);

                    byte[] byInc = new byte[] { 1, 0, 0, 0 };
                    byte[] byOut = new byte[4];
                    buffer = new byte[4096];
                    socket.IOControl(IOControlCode.ReceiveAll, byInc, byOut);
                    socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnReceive, null);
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                }

            }
            else
            {
                socket.Close();
                (sender as CheckBox).Text = "&Start me";
            }
        }
Esempio n. 8
0
        public AirservClient(string Host, int port)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(Host, port);

            client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, onBeginReceive, null);
        }
Esempio n. 9
0
        /**
         * Begins asynchronous receiving.
         *
         * @param receiveDel
         *   The callback to trigger when a packet is received.
         * @param disconnectDel
         *   The callback to trigger when an error occurs.
         */
        public void BeginReceive(PenguinReceiveCallback receiveCallback, PenguinDisconnectCallback disconnectCallback)
        {
            if (receiveCallback == null)
            {
                throw new System.ArgumentNullException("receiveCallback");
            }
            if (disconnectCallback == null)
            {
                throw new System.ArgumentNullException("disconnectCallback");
            }
            receiveCall    = receiveCallback;
            disconnectCall = disconnectCallback;
            BufferState receiveState = new BufferState();

            penguinSocks.BeginReceive(receiveState.Buffer, 0, receiveState.BufferSize, 0, ReceiveCallback, receiveState);
        }
Esempio n. 10
0
 // Start waiting for data from the client
 public void WaitForData(System.Net.Sockets.Socket soc)
 {
     try
     {
         if (BeginReceiveCallBack == null)
         {
             // Specify the call back function which is to be
             // invoked when there is any write activity by the
             // connected client
             BeginReceiveCallBack = new AsyncCallback(OnDataReceived);
         }
         SocketPacket theSocPkt = new SocketPacket();
         theSocPkt.currentSocket = soc;
         // Start receiving any data written by the connected client
         // asynchronously
         soc.BeginReceive(theSocPkt.dataBuffer, 0,
                          theSocPkt.dataBuffer.Length,
                          SocketFlags.None,
                          BeginReceiveCallBack,
                          theSocPkt);
     }
     catch (Exception ex)
     {
         ServerException(this, new ExceptionEventArgs(ex));
     }
 }
 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. 12
0
 private Socket SendingSocketCreator(IPEndPoint target)
 {
     var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     try
     {
         s.Connect(target);
         // Prep the socket so it will reset on close and won't Nagle
         s.LingerState = new LingerOption(true, 0);
         s.NoDelay = true;
         WriteConnectionPreemble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket
         // Start an asynch receive off of the socket to detect closure
         var foo = new byte[4];
         s.BeginReceive(foo, 0, 1, SocketFlags.None, ReceiveCallback,
             new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this));
         NetworkingStatisticsGroup.OnOpenedSendingSocket();
     }
     catch (Exception)
     {
         try
         {
             s.Dispose();
         }
         catch (Exception)
         {
             // ignore
         }
         throw;
     }
     return s;
 }
Esempio n. 13
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. 14
0
        public void RunReciever()
        {

            ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
            try
            {
                // Setup the Socket
                ListenSocket.Bind(new IPEndPoint(IPAddress.Parse(p_HostIP), 0));
                ListenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
                ListenSocket.IOControl(unchecked((int) 0x98000001), new byte[4] {1, 0, 0, 0}, new byte[4]);
                while (true) //Infinite Loop keeps the Socket in Listen
                {
                    ListenSocket.BeginReceive(p_PacketBuffer, 0, p_PacketBufferSize, SocketFlags.None,
                                                new AsyncCallback(CallReceive), this); 

                    while (ListenSocket.Available == 0) // If no Data Sleep the thread for 1ms then check to see if there is data to be read
                    {
                        Thread.Sleep(1);
                    }
                }
            }
            catch (ThreadAbortException){}// Catch the ThreadAbort Exception that gets generated whenever a thread is closed with the Thread.Abort() method
            catch (Exception e) {new ErrorHandle(e);}
            finally //Shutdown the Socket when finished
            {
                if (ListenSocket != null)
                {
                    ListenSocket.Shutdown(SocketShutdown.Both);
                    ListenSocket.Close();
                }
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect("localhost", 4530);

            //实现接受消息的方法
            var buffer = new byte[1024];//设置一个缓冲区,用来保存数据
            //socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback((ar) => 
            //{
            //    var length = socket.EndReceive(ar);
            //    var message = Encoding.Unicode.GetString(buffer, 0, length);
            //    //显示读出来的消息
            //    Console.WriteLine(message);
            //}), null);

            Console.WriteLine("Client connec to the server");
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            //接受用户输入,将消息发送给服务器端
            while (true)
            {
                var message = "message from client: " + Console.ReadLine();
                var outputBuffer = Encoding.Unicode.GetBytes(message);
                socket.BeginSend(outputBuffer, 0, outputBuffer.Length, SocketFlags.None, null, null);
            }
            Console.Read();
        }
Esempio n. 16
0
        // Start waiting for data from the client
        private void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (workerCallback == null)
                {
                    //Callback for data received from the client
                    workerCallback = new AsyncCallback(OnDataReceived);
                }

                SocketPacket theSocPkt = new SocketPacket();
                theSocPkt.currentSocket = soc;
                // Start receiving any data written by the connected client
                // asynchronously
                soc.BeginReceive(theSocPkt.dataBuffer, 0,
                                 theSocPkt.dataBuffer.Length,
                                 SocketFlags.None,
                                 workerCallback,
                                 theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
Esempio n. 17
0
 public XmppServerConnection(Form1 a, Socket sock)
     : this()
 {
     m_Sock = sock;
     frm = a;
     m_Sock.BeginReceive(buffer, 0, BUFFERSIZE, 0, new AsyncCallback(ReadCallback), null);
 }
Esempio n. 18
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);
            }
        }
Esempio n. 19
0
        /// <summary> This method opens a socket connection to the specified server.</summary>
        /// <returns> The return value is a string of the response from the server.</returns>
        public void Connect()
        {
            if (_connInfo == null)
            {
                throw new Exception("The SocketConnectionInfo class is null this is mandatory field.");
            }

            if (_connInfo.SocketProtocolType != ProtocolType.Tcp && _connInfo.IsTelnet)
            {
                throw new Exception("If you want to use the Telnet Protocol you must set your ProtocolType to \"TCP\".");
            }

            if (_connInfo.IPVersion == IpVersionType.IPv6 && !System.Net.Sockets.Socket.OSSupportsIPv6)
            {
                throw new Exception("Your system does not support IPv6\r\n" +
                                    "Check you have IPv6 enabled and have changed machine.config");
            }

            // Create a TCP/IP  socket.
            _socket = new System.Net.Sockets.Socket(_connInfo.IPVersion == IpVersionType.IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, _connInfo.SocketType, _connInfo.SocketProtocolType);
            //Connect
            _socket.Connect(_connInfo.IpEndPoint);
            //Store the cocket info once connected.
            _connInfo.Socket = _socket;

            _buffer       = new byte[1024];
            _receivedData = "";
            _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
        }
Esempio n. 20
0
 /// <summary>
 /// Receive data, remember to release the Stream
 /// </summary>
 /// <param name="socket">Socket</param>
 /// <returns>Stream</returns>
 public static MemoryStream ReadToStreamAsyn(Socket socket)
 {
     DataFlow flow = new DataFlow(socket);
     IAsyncResult asyncResult = socket.BeginReceive(flow.Buf, 0, flow.Buf.Length, SocketFlags.None, new AsyncCallback(AsyncRead), flow);
     flow.AutoEvent.WaitOne();
     return flow.MStream;
 }
Esempio n. 21
0
        public void JoinRoom(string userName, string targetIP)
        {
            try
            {
                strName = userName;
                ipInput = targetIP;
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ipAddress = IPAddress.Parse(ipInput);
                //Server is listening on port 1000
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);

                //Connect to the server
                clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);

                Debug.WriteLine("Username: " + strName);

                byteData = new byte[1024];
                //Start listening to the data asynchronously
                clientSocket.BeginReceive(byteData,
                                           0,
                                           byteData.Length,
                                           SocketFlags.None,
                                           new AsyncCallback(OnReceive),
                                           null);
            }
            catch (Exception exc) { Debug.WriteLine(exc.ToString()); }
        }
    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. 23
0
        /// <summary>
        /// Start listening for a single client connection.
        /// </summary>
        /// <remarks>
        /// Once the connection is made, the server will communicate with the
        /// client until the connection is lost or closed. At this point, it
        /// will begin listening for a new client.
        /// </remarks>
        public void Listen()
        {
            try
            {
                // Establish the local endpoint for the socket.
                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

                // Create a TCP/IP socket.
                listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Bind to the local endpoint.
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Block until a connection is accepted.
                Console.WriteLine("Waiting for a connection...");
                client = listener.Accept();
                Console.WriteLine("Connection Established.");

                // Begin receiving data from the client.
                client.BeginReceive(buffer, 0, BufferSize, 0, ReceiveCallback, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Esempio n. 24
0
 public PolicyConnection(PolicyServer policyServer, Socket client, byte[] policy)
 {
     _policyServer = policyServer;
     _connection = client;
     _endpoint = _connection.RemoteEndPoint;
     _policy = policy;
     _buffer = new byte[_policyRequestString.Length];
     _received = 0;
     try
     {
         // Receive the request from the client                
         _connection.BeginReceive(_buffer, 0, _policyRequestString.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
     }
     catch (SocketException ex)
     {
         if (log.IsDebugEnabled)
             log.Debug("Socket exception", ex);
         _connection.Close();
     }
     catch (Exception ex)
     {
         if (log.IsErrorEnabled)
             log.Error("Failed starting a policy connection", ex);
     }
 }
Esempio n. 25
0
        public Client(Socket acceptedSck)
        {
            sck = acceptedSck;
            ID = Guid.NewGuid().ToString();

            sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
        }
Esempio n. 26
0
        public bool Start()
        {
            if (_started) return true;

            _socket = SocketUtils.OpenSocketConnection("api.triggrapp.com", 9090);

            if (_socket == null)
            {
                _started = false;
                return false;
            }

            _started = true;

            StateObject state = new StateObject();
            state.workSocket = _socket;

            _socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

            SendHandshake();

            StartHeartbeat();

            return true;
        }
Esempio n. 27
0
        private void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }

                var stateObject = new StateObject(BufferLength);
                stateObject.workSocket = soc;

                soc.BeginReceive(
                    stateObject.buffer,
                    0,
                    stateObject.buffer.Length,
                    SocketFlags.None,
                    pfnWorkerCallBack,
                    stateObject);
            }
            catch (SocketException sex)
            {
                Debug.Fail(sex.ToString(), "WaitForData: Socket failed");
            }
        }
Esempio n. 28
0
        public void sendPackage(byte[] _data, Socket socket)
        {
            // DataPackage _data = new DataPackage("First package", 9999, true);
            // DroidMessage _data = new DroidMessage("Hello socket server");
            try
            {
                if (isOnline == true)
                {
                    byte[] data = _data;
                    //_clientSocket.Send(buffer);
                    // socket.Send(_data);

                    socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                    byte[] _buf = _buffersList.SingleOrDefault(k => k.Key == socket).Value;

                    // socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                    socket.BeginReceive(_buf, 0, _buf.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                }
            }
            catch (Exception ex)
            {
                if (OnServerError != null)
                {
                    OnServerError(null, new NotyArgs(ex.Message));
                }
            }
        }
Esempio n. 29
0
        public static FileReceiveStatus FileReceive(Socket socketFd)
        {
            //receive File size
            var sizeBytes = new byte[sizeof(int)];

            try
            {
                socketFd.Receive(sizeBytes, sizeBytes.Length, 0);
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception:\t\n" + exc.Message);
                var window = (ProjectZip)Application.OpenForms[0];
                window.SetControls(true);
            }

            var size = BitConverter.ToInt32(sizeBytes, 0);

            //receive File
            var fas = new FileAndSize
            {
                SizeRemaining = size,
                SocketFd = socketFd
            };

            socketFd.BeginReceive(fas.Buffer, 0, FileAndSize.BUF_SIZE, 0,  FileReceiveCallback, fas);

            return FileReceiveStatus.Ok;
        }
Esempio n. 30
0
        private void WaitForData(Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                CSocketPacket theSocPkt = new CSocketPacket(BufferLength);
                theSocPkt.thisSocket = soc;
                // now start to listen for any data...
                soc.BeginReceive(
                    theSocPkt.dataBuffer,
                    0,
                    theSocPkt.dataBuffer.Length,
                    SocketFlags.None,
                    pfnWorkerCallBack,
                    theSocPkt);
            }
            catch (SocketException sex)
            {
                Debug.Fail(sex.ToString(), "WaitForData: Socket failed");
            }

        }
Esempio n. 31
0
 public static void BeginReadPacket(Socket skt, ClientProcessor psr, Action<Packet> callback, Action failure)
 {
     byte[] n = new byte[5];
     skt.BeginReceive(n, 0, 5, 0, ar =>
     {
         try
         {
             byte[] x = (byte[])ar.AsyncState;
             int len = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(x, 0));
             if (len == 0)
             {
                 failure();
                 return;
             }
             len -= 5;
             byte id = x[4];
             Packet packet = Packets[(PacketID)id].CreateInstance();
             byte[] content = new byte[len];
             if (len > 0)
                 skt.Receive(content);
             packet.Read(psr, new NReader(new MemoryStream(packet.Crypt(psr, content))));
             callback(packet);
         }
         catch { failure(); }
     }, n);
 }
Esempio n. 32
0
        public Client(Socket socket, Program program)
        {
            _socket = socket;
             _program = program;

             socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallback, null);
        }
 // Start waiting for data from the client
 public void WaitForData(System.Net.Sockets.Socket soc)
 {
     try
     {
         if (pfnWorkerCallBack == null)
         {
             // Specify the call back function which is to be
             // invoked when there is any write activity by the
             // connected client
             pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
         }
         SocketPacket theSocPkt = new SocketPacket();
         theSocPkt.m_currentSocket = soc;
         // Start receiving any data written by the connected client
         // asynchronously
         soc.BeginReceive(theSocPkt.dataBuffer, 0,
                          theSocPkt.dataBuffer.Length,
                          SocketFlags.None,
                          pfnWorkerCallBack,
                          theSocPkt);
     }
     catch (SocketException se)
     {
         MessageBox.Show(se.Message);
     }
 }
Esempio n. 34
0
 // Start waiting for data from the client
 public static void WaitForData(System.Net.Sockets.Socket soc)
 {
     try
     {
         if (pfnWorkerCallBack == null)
         {
             // Specify the call back function which is to be
             // invoked when there is any write activity by the
             // connected client
             pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
         }
         SocketPacket theSocPkt = new SocketPacket();
         theSocPkt.m_currentSocket = soc;
         // Start receiving any data written by the connected client
         // asynchronously
         soc.BeginReceive(theSocPkt.dataBuffer, 0,
                          theSocPkt.dataBuffer.Length,
                          SocketFlags.None,
                          pfnWorkerCallBack,
                          theSocPkt);
     }
     catch (SocketException se)
     {
         Globals.l2net_home.Add_Text("Errror: Wait for data, exception: " + se.Message, Globals.Red, TextType.BOT);
     }
 }
Esempio n. 35
0
		public WebsocketClient (Socket s)
		{
			this.bufferStrBuild = new StringBuilder();
			clientSocket = s;
			s.BeginReceive( this.buffer, 0, BUFFER_SIZE, 0,
			                     new AsyncCallback(this.ReadCallback), this);
		}
Esempio n. 36
0
        void OnNewClient(IAsyncResult _asyncResult)
        {
            System.Net.Sockets.Socket ClientSocket = ListenSocket.EndAccept(_asyncResult);
            ListenSocket.BeginAccept(OnNewClient, null);

            SetKeepAlive(ClientSocket, 1000 * 60, 1000);

            var NewClient = new TelnetClient {
                Socket = ClientSocket
            };

            if (Clients.ClientConnected(NewClient) == ClientAcceptanceStatus.Rejected)
            {
                NewClient.WasRejected = true;
                ClientSocket.Close();
            }
            else
            {
                // We will handle all the echoing echoing echoing
                //var echoCommand = new byte[]
                //{
                //    (byte)TelnetControlCodes.IAC,
                //    (byte)TelnetControlCodes.Will, // TODO: Handle client response denying this request
                //    (byte)TelnetControlCodes.Echo,
                //    (byte)TelnetControlCodes.IAC,
                //    (byte)TelnetControlCodes.Dont,
                //    (byte)TelnetControlCodes.Echo,
                //};
                //ClientSocket.Send(echoCommand);

                ClientSocket.BeginReceive(NewClient.Storage, 0, 1024, System.Net.Sockets.SocketFlags.Partial, OnData, NewClient);
                Console.WriteLine("New telnet client: " + ClientSocket.RemoteEndPoint.ToString());
            }
        }
 public void init()
 {
     try
     {
         Console.WriteLine("Init");
         //set up socket
         Socket client = new Socket(AddressFamily.InterNetwork,
         SocketType.Stream, ProtocolType.Tcp);
         //IPHostEntry hostInfo = Dns.Resolve("localhost:8000");
         //IPAddress address = hostInfo.AddressList[0];
         //IPAddress ipAddress = Dns.GetHostEntry("localhost:8000").AddressList[0];
         IPAddress ipAddress = new IPAddress(new byte[] { 128, 61, 105, 215 });
         IPEndPoint ep = new IPEndPoint(ipAddress, 8085);
         client.BeginConnect(ep, new AsyncCallback(ConnectCallback), client);
         connectDone.WaitOne();
         //receiveForever(client);
         byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
         StateObject state = new StateObject();
         state.workSocket = client;
         client.BeginReceive(buffer, 0, StateObject.BufferSize, 0,
                 new AsyncCallback(ReceiveCallback), state);
         client.Send(msg);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
Esempio n. 38
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
                //Server is listening on port
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, Convert.ToInt32(txtPort.Text));

                //Connect to the server
                clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);

                byteData = new byte[1024];
                //Start listening to the data asynchronously
                clientSocket.BeginReceive(byteData,
                                           0,
                                           byteData.Length,
                                           SocketFlags.None,
                                           new AsyncCallback(OnReceive),
                                           null);
                btnOK.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ChatClient", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 39
0
        public void Connect(int aPort, IPAddress Ip, string userName, string password, string nick)
        {
            int attempts = 5;
            _nick = nick;

            // TODO: validar esse objeto, pois após a desconexão ocorre o dispose() dele
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            while (!_clientSocket.Connected && attempts > 0)
            {
                try
                {
                    OnRaiseMessage(new MessageEventArgs(String.Format("Attempt {0} to connect at server {1}:{2}", attempts, Ip.MapToIPv4().Address, aPort)));
                    _clientSocket.Connect(Ip ,aPort);
                    OnRaiseMessage(new MessageEventArgs("Connected!"));

                    //solicita autenticação
                    Authenticate(userName, password);

                    //inicia recebimento assíncrono de mensagens
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket);

                }
                catch (Exception ex)
                {
                    OnRaiseMessage(new MessageEventArgs("Connection failed."));
                    Thread.Sleep(1000);
                    attempts--;
                }
            }
        }
        public bool StartAsyncReceiving()
        {
            if (!socket.Connected)
            {
                return(false);
            }

            var receiveBuffer = new byte[4096];

            receivedBinaryStream = new System.IO.MemoryStream();
            int offset = 0;

            socket.BeginReceive(receiveBuffer, offset, receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), receiveBuffer);

            return(true);
        }
Esempio n. 41
0
        public void Accept(IAsyncResult ar)
        {
            clientSocket = (ar.AsyncState as TcpListener).EndAcceptSocket(ar);
            realm.threadManager.Set();

            clientSocket.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, Receive, clientSocket);
        }
Esempio n. 42
0
        private static IEnumerator<IAsyncCall> Echo(Socket client)
        {
            byte[] buffer = new byte[1024];
            AsyncCall<int> call = new AsyncCall<int>();

            while (true)
            {
                yield return call
                    .WaitOn(cb => client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, cb, null))
                    & client.EndReceive;

                int bytes = call.Result;
                if (bytes > 0)
                {
                    Console.WriteLine("read {0} bytes from {1}", bytes, client.RemoteEndPoint);

                    yield return call
                        .WaitOn(cb => client.BeginSend(buffer, 0, bytes, SocketFlags.None, cb, null))
                        & client.EndReceive;

                    Console.WriteLine("sent {0} bytes to {1}", bytes, client.RemoteEndPoint);
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("closing client socket {0}", client.RemoteEndPoint);

            client.Close();
        }
        private void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }

                CSocketPacket theSocPkt = new CSocketPacket(BufferLength);
                theSocPkt.thisSocket = soc;

                // now start to listen for any data...
                soc.BeginReceive(
                    theSocPkt.dataBuffer,
                    0,
                    theSocPkt.dataBuffer.Length,
                    SocketFlags.None,
                    pfnWorkerCallBack,
                    theSocPkt);
            }
            catch (SocketException sex)
            {
                Debug.Fail(sex.ToString(), "WaitForData: Socket failed");
            }
        }
        public void Start(IPEndPoint dest)
        {
            this.destination = dest;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

            socket.Connect(dest);
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveTcpData, null);

            DataPacket p = DataPacket.Create(16);
            p.Command = (ushort)CommandID.CA_PROTO_VERSION;
            p.DataType = 1;
            p.DataCount = (uint)EpicsConstants.CA_MINOR_PROTOCOL_REVISION;
            p.Parameter1 = 0;
            p.Parameter2 = 0;
            Send(p);

            p = DataPacket.Create(16 + this.Client.Configuration.Hostname.Length + TypeHandling.Padding(this.Client.Configuration.Hostname.Length));
            p.Command = (ushort)CommandID.CA_PROTO_HOST_NAME;
            p.DataCount = 0;
            p.DataType = 0;
            p.Parameter1 = 0;
            p.Parameter2 = 0;
            p.SetDataAsString(this.Client.Configuration.Hostname);
            Send(p);

            p = DataPacket.Create(16 + this.Client.Configuration.Username.Length + TypeHandling.Padding(this.Client.Configuration.Username.Length));
            p.Command = (ushort)CommandID.CA_PROTO_CLIENT_NAME;
            p.DataCount = 0;
            p.DataType = 0;
            p.Parameter1 = 0;
            p.Parameter2 = 0;
            p.SetDataAsString(this.Client.Configuration.Username);
            Send(p);
        }
Esempio n. 45
0
            void HandleRead()
            {
                SocketError se;
                int         length = (int)Math.Min(readLimit, receiveBuffer.Length);

                socket.BeginReceive(receiveBuffer, 0, length, SocketFlags.None, out se, ReadCallback, null);
            }
Esempio n. 46
0
        IWaitableValue <int> IStreamable.Receive(byte[] readed_byte, int offset, int count)
        {
            /*if (!Socket.Connected)
             * {
             *  _SocketErrorEvent( SocketError.SocketError);
             *  return (0).ToWaitableValue();
             * }*/

            SocketError error;
            var         ar = Socket.BeginReceive(readed_byte, offset, count, SocketFlags.None, out error, _EndReceiveEmpty, null);

            var safeList = new[] { SocketError.Success, SocketError.IOPending };

            if (!safeList.Any(s => s == error))
            {
                _SocketErrorEvent(error);
            }

            if (ar == null)
            {
                return((0).ToWaitableValue());
            }

            return(System.Threading.Tasks.Task <int> .Factory.FromAsync(ar, _EndReceive).ToWaitableValue());
        }
Esempio n. 47
0
        private void Client_Form_Load(object sender, EventArgs e)
        {
            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                //Server is listening on port 1000
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);

                //Connect to the server
                clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            byteData = new byte[1024];
            //Start listening to the data asynchronously
            clientSocket.BeginReceive(byteData,
                                       0,
                                       byteData.Length,
                                       SocketFlags.None,
                                       new AsyncCallback(OnReceive),
                                       null);
        }
Esempio n. 48
0
 void HandleThreadStart()
 {
     try {
         TCL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 10112));
         TCL.Start();
         do
         {
             try {
                 System.Net.Sockets.Socket S = TCL.AcceptSocket();
                 FeuerwehrCloud.Helper.Logger.WriteLine("|  < [FAX] *** Incoming notification");
                 S.Blocking = false;
                 S.BeginReceive(buffer, 0, DEFAULT_SIZE - dataRecieved,
                                System.Net.Sockets.SocketFlags.None, new AsyncCallback(HandleAsyncCallback), S);
                 if (IsTerminating)
                 {
                     break;
                 }
             } catch (Exception e2x) {
             }
         } while (true);
     } catch (Exception ex) {
         if (ex.Message.Contains("already in use"))
         {
             FeuerwehrCloud.Helper.Logger.WriteLine("Kann FeuerwehrCloud-Server FaxModul nicht starten!");
         }
     }
 }
Esempio n. 49
0
 public MainWindow(Socket socket, string username)
 {
     InitializeComponent();
     this.socket = socket;
     this.username = username;
     sendString("username;" + username);
     socket.BeginReceive(buffer, 0, BUFFERSIZE, SocketFlags.None, onDataRecieved, null);
 }
Esempio n. 50
0
        //: base(ClientSocket, (Listener)Server)
        public LoginClient(Socket ClientSocket, LoginListener Server)
        {
            m_Socket = ClientSocket;
            m_Listener = Server;

            m_Socket.BeginReceive(m_RecvBuffer, 0, m_RecvBuffer.Length, SocketFlags.None,
                new AsyncCallback(OnReceivedData), m_Socket);
        }
Esempio n. 51
0
        /// <summary>
        /// 建立Tcp连接后处理函数
        /// </summary>
        /// <param name="iar">异步Socket</param>
        protected void Connected(IAsyncResult iar)
        {
            System.Net.Sockets.Socket socket = null;
            try
            {
                socket = (System.Net.Sockets.Socket)iar.AsyncState;
                socket.EndConnect(iar);

                //设置连接状态
                isConnection = true;
                //获取本机端口
                this._LoadProt = ((IPEndPoint)sock.LocalEndPoint).Port;
                //触发连接成功事件
                if (ClientConn != null)
                {
                    ClientConn("Success");
                }

                //判断是否开启心跳机制
                if (this.IsHeartbeat)
                {
                    if (Heartbeat_Thread == null)
                    {
                        HeartbeatTime    = DateTime.Now;
                        Heartbeat_Thread = new System.Threading.Thread(Heartbeat);
                        Heartbeat_Thread.IsBackground = true;
                        Heartbeat_Thread.Start();
                    }
                }
            }
            catch (SocketException e)
            {
                isConnection = false;
                //触发连接失败事件
                if (ClientConnCut != null)
                {
                    ClientConnCut("Fail-EX:" + e.Message);
                }
                return;
            }

            ///////////////////////////////////////////
            ///开启接收数据监控
            ///////////////////////////////////////////
            try
            {
                socket.BeginReceive(ReceiveDataBuffer, 0, ReceiveBufferSize, SocketFlags.None, new AsyncCallback(RecvData), socket);
            }
            catch (Exception e)
            {
                isConnection = false;
                //触发连接失败事件
                if (ClientConnCut != null)
                {
                    ClientConnCut("Fail-EX:" + e.Message);
                }
            }
        }
Esempio n. 52
0
 public void SetupRecieveCallback(RecievedDataDelegate OnReceive)
 {
     try{
         AsyncCallback recieveData = new AsyncCallback(OnReceive);
         m_sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, this);
     }
     catch (Exception ex) {
         Console.WriteLine("Recieve callback setup failed! {0}", ex.Message);
     }
 }
Esempio n. 53
0
        private void _readData()
        {
            Core.EventLoop.Instance.Push(() =>
            {
                _recv = new byte[CHUNK];

                nativeSocket.BeginReceive(_recv, 0, CHUNK,
                                          Winsock.SocketFlags.None, _static_endReceive, this);
            });
        }
Esempio n. 54
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. 55
0
 void IPeer.Receive(byte[] readed_byte, int offset, int count, Action <int> done)
 {
     try
     {
         _Socket.BeginReceive(readed_byte, offset, count, SocketFlags.None, this.Readed, state: done);
     }
     catch (Exception e)
     {
         _Enable = false;
     }
 }
Esempio n. 56
0
File: Users.cs Progetto: kadir1/DoPs
        public User(System.Net.Sockets.Socket handler)
        {
            this.handler = handler;
            Do.Core.StateObject state = new Do.Core.StateObject();
            state.workSocket = handler;

            this.IP = handler.RemoteEndPoint.ToString().Split(':')[0];

            handler.BeginReceive(buffer, 0, buffer.Length, 0,
                                 new AsyncCallback(ReadCallback), this);
        }
Esempio n. 57
0
 public void Receive(System.Net.Sockets.Socket sock)
 {
     try
     {
         sock.BeginReceive(m_msg_header, 0, 4, SocketFlags.None,
                           new AsyncCallback(OnReceived), sock);
     }
     catch (Exception ex)
     {
         Console.Write("Receive failed!");
     }
 }
Esempio n. 58
0
        public void BeginReceive()
        {
            var stateObject = new AsyncStateObject(m_socket);

            m_socket.BeginReceive(
                stateObject.ReceiveBuffer,
                0,
                stateObject.ReceiveBuffer.Length,
                SocketFlags.None,
                new AsyncCallback(ReceiveDataCallback),
                stateObject);
        }
Esempio n. 59
0
        Byte[] _buffer = new Byte[1024 * 100]; // 100k

        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                // now start to listen for any data...
                soc.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), this);
            }
            catch (SocketException se)
            {
                System.Diagnostics.Debugger.Log(0, "1", se.Message);
            }
        }
Esempio n. 60
-1
 public Connection(GameServer server, Socket socket)
 {
     _socket = socket;
     _server = server;
     _socket.BeginReceive(buffer, 0, 256, SocketFlags.None, new AsyncCallback(ReceiveData), _socket);
     _socket.BeginDisconnect(false, new AsyncCallback(Disconnect), null);
 }