Esempio n. 1
0
        private void StartDataReceive(bool firstTime)
        {
            if (socket == null)
            {
                return;
            }

            if (firstTime)
            {
                receiveOffset = 0;
            }
            else if (receiveOffset >= receiveBuffer.Length)
            {
                // There is nothing more to receive in the buffer, and to prevent getting stuck, we simply reset the receive offset
                // This should never happen though...
                receiveOffset = 0;
            }

            try
            {
                socket?.BeginReceive(receiveBuffer, receiveOffset, receiveBuffer.Length - receiveOffset, SocketFlags.None, OnDataReceived, socket);
            }
            catch (ObjectDisposedException)
            {
                // NOTE: If the socket as been disposed of, then we can safely discard this exception and just stop listen
            }
            catch (Exception ex)
            {
                Log.LogDebugException(ex);
                Disconnect();
            }
        }
Esempio n. 2
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                if (socket != null)
                {
                    int    len            = socket.EndReceive(ar);
                    byte[] receivedBuffer = new byte[len];
                    Array.Copy(buffer, 0, receivedBuffer, 0, len);

                    try
                    {
                        Packet packet = new Packet(receivedBuffer);
                        OnNewPacket(packet);
                    }
                    catch (ArgumentNullException ane)
                    {
                        Console.WriteLine(ane.ToString());
                    }
                    catch (ArgumentException ae)
                    {
                        Console.WriteLine(ae.ToString());
                    }
                }

                socket?.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
            }
            catch
            {
                Stop();
            }
        }
Esempio n. 3
0
        private void WaitForServerData(IAsyncResult ar)
        {
            if (_isClosing || !_doPacketProcess)
            {
                return;
            }
            Socket worker = null;

            try
            {
                worker = (Socket)ar.AsyncState;
                var rcvdBytes = worker.EndReceive(ar);
                if (rcvdBytes > 0)
                {
                    _remoteRecvBuffer.Size = rcvdBytes;
                    _remoteSecurity.Recv(_remoteRecvBuffer);
                }
                else
                {
                    //RaiseEvent
                    if (Kicked != null)
                    {
                        Kicked();
                        worker = null;
                    }
                    else
                    {
                        Console.WriteLine("You have been kicked by the Security Software.");
                    }
                }
            }
            catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.ConnectionReset) //Disconnected
                {
                    Console.WriteLine("You have been disconnected from the Server.");

                    //RaiseEvent
                    Disconnected?.Invoke();

                    //Mark worker as null to stop reciving
                    worker = null;
                }
                else
                {
                    Console.WriteLine(se.ErrorCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                worker?.BeginReceive(_remoteRecvBuffer.Buffer, 0, 8192, SocketFlags.None, WaitForServerData,
                                     worker);
            }
        }
Esempio n. 4
0
 private void StartPipe()
 {
     if (_closed)
     {
         return;
     }
     try
     {
         _startReceivingTime = DateTime.Now;
         remote?.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeRemoteReceiveCallback), null);
         connection?.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeConnectionReceiveCallback), null);
     }
     catch (Exception e)
     {
         Logging.LogUsefulException(e);
         Close();
     }
 }
Esempio n. 5
0
 private void StartPipe(AsyncSession session)
 {
     if (_closed)
     {
         return;
     }
     try
     {
         _startReceivingTime = DateTime.Now;
         session.Remote.BeginReceive(_remoteRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeRemoteReceiveCallback), session);
         connection?.BeginReceive(_connetionRecvBuffer, 0, RecvSize, SocketFlags.None, new AsyncCallback(PipeConnectionReceiveCallback),
                                  new AsyncSession <bool>(session, true) /* to tell the callback this is the first time reading packet, and we haven't found the header yet. */);
     }
     catch (Exception e)
     {
         Logging.LogUsefulException(e);
         Close();
     }
 }
    public Client(Socket accepted)
    {
        sck = accepted;
        ID = Guid.NewGuid().ToString();

        EndPoint = (IPEndPoint)sck.RemoteEndPoint;
        sck.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);

        confirmConnect();
    }
Esempio n. 7
0
 void prepareForReceive(Socket socket, Action<string> onReceive)
 {
     var buffer = new byte[socket.ReceiveBufferSize];
     socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
         ar => {
             var client = (Socket)ar.AsyncState;
             var bytesReceived = client.EndReceive(ar);
             var trimmedBuffer = new byte[bytesReceived];
             Array.Copy(buffer, trimmedBuffer, bytesReceived);
             onReceive(Encoding.UTF8.GetString(trimmedBuffer));
         }, socket);
 }
Esempio n. 8
0
 private void Receive(Socket client)
 {
     try
     {
         StateObject state = new StateObject();
         state.workSocket = client;
         client.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReceiveCallback), state);
     }
     catch (Exception e)
     {
         Debug.LogException(e);
     }
 }
Esempio n. 9
0
 private void SendData(IAsyncResult result)
 {
     try
     {
         Socket?clientSocket = (Socket?)result.AsyncState;
         clientSocket?.EndSend(result);
         clientSocket?.BeginReceive(m_data, 0, m_dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
     }
     catch (Exception ex)
     {
         Console.Error.WriteLine(ex.Message);
     }
 }
Esempio n. 10
0
    private static void Receive(Socket client)
    {
        try {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
    }
Esempio n. 11
0
        private void WaitForData(IAsyncResult ar)
        {
            if (_isClosing || !_doPacketProcess)
            {
                return;
            }
            Socket worker = null;

            try
            {
                worker = (Socket)ar.AsyncState;
                var rcvdBytes = worker.EndReceive(ar);
                if (rcvdBytes > 0)
                {
                    _localRecvBuffer.Size = rcvdBytes;
                    _localSecurity.Recv(_localRecvBuffer);
                }
                else
                {
                    //Console.WriteLine("Client Disconnected");
                    Disconnected?.Invoke();
                    Listen();
                }
            }
            catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.ConnectionReset) //Client Disconnected
                {
                    //Console.WriteLine("Client Disconnected");
                    //RaisEvent
                    Disconnected?.Invoke();
                    Listen();

                    //Mark worker as null to stop reciveing.
                    worker = null;
                }
                else
                {
                    throw new Exception("Proxy.Network.Client.WaitForData: " + se.Message, se);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Proxy.Network.Client.WaitForData: " + ex.Message, ex);
            }
            finally
            {
                worker?.BeginReceive(_localRecvBuffer.Buffer, 0, 8192, SocketFlags.None, WaitForData, worker);
            }
        }
Esempio n. 12
0
 private NetIO()
 {
     try
     {
         //创建客户端连接
         socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         //连接到服务器
         socket.Connect(ip, port);
         //开启异步接收,消息到达会直接写入缓冲区
         socket.BeginReceive(readBuff, 0, 1024, SocketFlags.None, ReceiveCallBack, readBuff);
     }
     catch (Exception e)
     {
         Debug.Log(e.Message);
     }
 }
Esempio n. 13
0
    public static void AcceptCallback(IAsyncResult ar)
    {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        connectSocket = (Socket) ar.AsyncState;
        connectSocket = connectSocket.EndAccept(ar);

        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = connectSocket;
        connectSocket.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
        Send(connectSocket, "Hello!");
        Debug.Log("[ROTATION_SERVER] Sent INIT sequence to client.");
    }
Esempio n. 14
0
    private void Connected(IAsyncResult iar)
    {
        client = (Socket)iar.AsyncState;
        try
        {
            client.EndConnect(iar);

            sendAuthLogonChallenge();

            client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
        }
        catch (SocketException)
        {
            Console.WriteLine("Connection failed");
            // Error connecting
        }
    }
Esempio n. 15
0
    private static void Receive(Socket client)
    {
        try
        {
            StateObject state = new StateObject();
            state.workSocket = client;

            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception ex)
        {
            if (ex.Message == "No connection could be made because the target machine actively refused it")
                Console.WriteLine("File Sending fail. Because server not running?");
            else
                Console.WriteLine("File Sending fail. " + ex.Message);
        }
    }
Esempio n. 16
0
	public void connectServer(){
		try{
			/*
			GameWorld gw= GameWorld.getInstance();
			string serverid ="server1";
			LitJson.JsonData server_info =gw.getServerInfo(serverid);
            Debug.Log(server_info["host"]+"================================"+server_info["port"]);
            int port = int.Parse(server_info["port"].ToString());
			string host=(server_info["host"]).ToString();
			*/
			string host = "127.0.0.1";
			int port = 9301;
			IPAddress ipad=IPAddress.Parse(host);
			IPEndPoint ipend=new IPEndPoint(ipad,port);

			//create connection
			sc= new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
			Debug.Log("begin connect server "+host+":"+port);

			sc.Connect(ipend);

			//send msg to server
			string sendmsg="hello conenct";
			byte[] bs=Encoding.UTF8.GetBytes(sendmsg);

			sc.Send(bs,bs.Length,0);

			Debug.Log("------------CONNECT over-------------------");
            isConnected = true;
            if (sc.Connected) {
                Debug.Log("begin recive msg from server=================================");
                sc.BeginReceive(receiveBuff,0,receiveBuff.Length,0,new AsyncCallback(reciveMessageCallBack),null);
            }
            
		}
		catch(ArgumentNullException e){
			//Debug.Log ("ArgumentNullException : "+e.ToString());
            throw e;
		}
		catch(SocketException e){
			//Debug.Log ("SocketException : "+e.ToString());
            throw e;
		}
	}
Esempio n. 17
0
        /// <summary>
        /// Peer read packet asynchronous callback.
        /// </summary>
        /// <param name="readAsyncState">Read async state.</param>
        private void ReadAsyncHandler(IAsyncResult readAsyncState)
        {
            Peer remotePeer = (Peer)readAsyncState.AsyncState;

            try
            {
                SocketError socketError = SocketError.Success;
                int?        bytesRead   = _socket?.EndReceive(readAsyncState, out socketError);
                ThrowOnError((_socket is null) || (bytesRead <= 0) || !_socket.Connected, socketError);
                _bytesRead += (int)bytesRead;
                if (!_lengthRead)
                {
                    if (_bytesRead == Constants.SizeOfUInt32)
                    {
                        PacketLength = (int)Util.UnPackUInt32(ReadBuffer, 0);
                        _lengthRead  = true;
                        _bytesRead   = 0;
                        if (PacketLength > ReadBuffer.Length)
                        {
                            Log.Logger.Debug("Resizing readBuffer ...");
                            ReadBuffer = new byte[PacketLength];
                        }
                    }
                }
                else if (_bytesRead == PacketLength)
                {
                    remotePeer.ProtocolHandler(remotePeer);
                    _lengthRead  = false;
                    _bytesRead   = 0;
                    PacketLength = Constants.SizeOfUInt32;
                }
                _socket?.BeginReceive(ReadBuffer, _bytesRead, (PacketLength - _bytesRead), SocketFlags.None, new AsyncCallback(ReadAsyncHandler), remotePeer);
                ThrowOnError((_socket is null) || (bytesRead <= 0) || !_socket.Connected, socketError);
            }
            catch (Exception ex)
            {
                Log.Logger.Debug("Error (Ignored): " + ex.Message);
                Log.Logger.Info($"Read packet handler {Encoding.ASCII.GetString(remotePeer.RemotePeerID)} terminated.");
                remotePeer.Close();
            }
        }
Esempio n. 18
0
	private void Read(Socket client, bool beginNewPhase)
	{
		try {
			// Begin receiving the data from the remote device.
			if (beginNewPhase)
			{
				mState.bytesRead = 0;
				client.BeginReceive( mState.readBuffer, 0, JStateObject.BufferSize,
				                    0,
				                    new AsyncCallback(ReadCallback), mState);
			}
			else
			{
				client.BeginReceive( mState.readBuffer, 0, JStateObject.BufferSize - mState.bytesRead,
				                    0,
				                    new AsyncCallback(ReadCallback), mState);
			}
		} catch (Exception e) {
			//Console.WriteLine(e.ToString());
			Debug.Log("C: Receive " + e.ToString());
		}
	}
Esempio n. 19
0
 public void JoinServer()
 {
     YourSocket = new Socket(AddressFamily.InterNetwork,
                             SocketType.Stream,
                             ProtocolType.IP);
     try {
         YourSocket.Connect(IpText.text,
                            NetworkConnector.Port);
         this.LocalPlayer[0] = false;
         this.LocalPlayer[1] = true;
         this.IsConnected = true;
         YourSocket.BeginReceive(this.SocketBuffer,
                                 0,
                                 this.SocketBuffer.Length,
                                 SocketFlags.None,
                                 new System.AsyncCallback(this.OnSocketRead),
                                 null);
     }
     catch{
         Debug.Log("Join Failed!");
     }
 }
Esempio n. 20
0
        public void RecieveCallBack(IAsyncResult ar)
        {
            try
            {
                Socket      socket = ar.AsyncState as Socket;
                SocketError sockErr;
                if (socket != null)
                {
                    int received = socket.EndReceive(ar, out sockErr);
                    if (sockErr != SocketError.Success)
                    {
                        received = 0;
                    }

                    if (received > 0)
                    {
                        byte[] dataBuff = new byte[received];
                        Array.Copy(Buffer, dataBuff, received);

                        _text = Encoding.ASCII.GetString(dataBuff, 0, dataBuff.Length);
                        //dump text into received data table
                        _ta.Insert(_text, DateTime.Now);


                        socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, RecieveCallBack, socket);
                        ServerSocket.BeginAccept(AcceptCallBack, null);
                    }
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine(@"SocketException RecieveCallBack Err: " + ex.Message);

                Socket socket = ar.AsyncState as Socket;
                socket?.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, RecieveCallBack, socket);
                ServerSocket.BeginAccept(AcceptCallBack, null);
            }
        }
Esempio n. 21
0
	public void Connect(string name) {
		queue = new Queue<string>();
		
		IPAddress address = Dns.Resolve(host).AddressList[0];
		IPEndPoint remote = new IPEndPoint(address, port);
		
		pull = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		pull.NoDelay = true;
		pull.Connect(remote);
		
		String data = "GET /pull?name=" + name + " HTTP/1.1\r\n"
			+ "Host: " + host + "\r\n"
				+ "Head: less\r\n\r\n"; // enables TCP no delay
		
		pull.Send(Encoding.ASCII.GetBytes(data));
		
		State state = new State();
		state.socket = pull;
		
		pull.BeginReceive(state.data, 0, State.size, 0, new AsyncCallback(Callback), state);
		
		connected = true;
	}
        void OnSocketReceive(IAsyncResult ar)
        {
            Socket client = null;
            int    bytes  = 0;

            try
            {
                client = (Socket)ar.AsyncState;
                bytes  = client.EndReceive(ar);

                client.BeginReceive(socketBuffer, 0, socketBuffer.Length, SocketFlags.None, OnSocketReceive, client);


                string   text          = Encoding.UTF8.GetString(socketBuffer, 0, bytes);
                string   sep           = "/";
                string[] remoteMessage = text.Split('/');
                string   action        = remoteMessage[0];
                string   variable      = remoteMessage[1];
                if (action.Equals("play"))
                {
                    variable = variable.Replace('*', '/');
                }

                Banshee.Collection.TrackInfo currTrack = ServiceManager.PlayerEngine.CurrentTrack;
                string replyText = "";
                ushort currVol;
                ushort volStep   = 10;
                bool   replyReq  = false;
                string home      = Environment.GetEnvironmentVariable("HOME");
                string coverPath = "";
                string dbPath    = home + "/.config/banshee-1/banshee.db";
                if (currTrack != null && currTrack.ArtworkId != null)
                {
                    coverPath = home + "/.cache/media-art/" + currTrack.ArtworkId.ToString() + ".jpg";
                }

                switch (action)
                {
                case "coverImage":
                    byte[] coverImage = File.ReadAllBytes(coverPath);
                    client.Send(coverImage);
                    replyReq = true;
                    break;

                case "syncCount":
                    int count = System.IO.File.ReadAllBytes(dbPath).Length;
                    client.Send(System.Text.Encoding.UTF8.GetBytes(count.ToString()));
                    replyReq = true;
                    break;

                case "sync":
                    byte[] db = File.ReadAllBytes(dbPath);
                    client.Send(db);
                    replyReq = true;
                    break;

                case "coverExists":
                    replyText = coverExists(coverPath);
                    replyReq  = true;
                    break;

                case "playPause":
                    ServiceManager.PlayerEngine.TogglePlaying();
                    replyReq = true;
                    break;

                case "next":
                    ServiceManager.PlaybackController.Next();
                    replyReq = true;
                    break;

                case "prev":
                    ServiceManager.PlaybackController.Previous();
                    replyReq = true;
                    break;

                case "play":
                    var source = ServiceManager.SourceManager.MusicLibrary as DatabaseSource;
                    source.FilterQuery = "";
                    if (source != null)
                    {
                        var countSongs = source.Count;

                        UnknownTrackInfo track     = new UnknownTrackInfo(new SafeUri(variable));
                        TrackInfo        trackTemp = null;
                        for (int i = 0; i < countSongs; i++)
                        {
                            trackTemp = source.TrackModel [i];
                            if (trackTemp.TrackEqual(track))
                            {
                                break;
                            }
                        }
                        if (trackTemp != null)
                        {
                            ServiceManager.PlayerEngine.OpenPlay(trackTemp);
                        }
                    }
                    replyReq = true;
                    break;

                case "volumeDown":
                    currVol = ServiceManager.PlayerEngine.Volume;
                    if (currVol < 10)
                    {
                        ServiceManager.PlayerEngine.Volume = 0;
                    }
                    else
                    {
                        ServiceManager.PlayerEngine.Volume = (ushort)(currVol - volStep);
                    }
                    replyReq = true;
                    break;

                case "volumeUp":
                    currVol = ServiceManager.PlayerEngine.Volume;
                    if (currVol > 90)
                    {
                        ServiceManager.PlayerEngine.Volume = 100;
                    }
                    else
                    {
                        ServiceManager.PlayerEngine.Volume = (ushort)(currVol + volStep);
                    }
                    replyReq = true;
                    break;

                case "mute":
                    currVol = ServiceManager.PlayerEngine.Volume;
                    if (currVol > 0)
                    {
                        volume = currVol;
                        ServiceManager.PlayerEngine.Volume = 0;
                    }
                    else
                    {
                        ServiceManager.PlayerEngine.Volume = volume;
                    }
                    replyReq = true;
                    break;

                case "status":
                    replyText = ServiceManager.PlayerEngine.CurrentState.ToString().ToLower();
                    replyReq  = true;
                    break;

                case "album":
                    replyText = currTrack.DisplayAlbumTitle;
                    replyReq  = true;
                    break;

                case "artist":
                    replyText = currTrack.DisplayArtistName;
                    replyReq  = true;
                    break;

                case "title":
                    replyText = currTrack.DisplayTrackTitle;
                    replyReq  = true;
                    break;

                case "trackCurrentTime":
                    replyText = (ServiceManager.PlayerEngine.Position / 1000).ToString();
                    replyReq  = true;
                    break;

                case "trackTotalTime":
                    replyText = currTrack.Duration.ToString();
                    replyReq  = true;
                    break;

                case "seek":
                    ServiceManager.PlayerEngine.Position = UInt32.Parse(variable) * 1000;
                    replyReq = true;
                    break;

                case "shuffle":
                    if (ServiceManager.PlaybackController.ShuffleMode.ToString() == "off")
                    {
                        ServiceManager.PlaybackController.ShuffleMode = "song";
                        replyText = "song";
                    }
                    else if (ServiceManager.PlaybackController.ShuffleMode.ToString() == "song")
                    {
                        ServiceManager.PlaybackController.ShuffleMode = "artist";
                        replyText = "Artist";
                    }
                    else if (ServiceManager.PlaybackController.ShuffleMode.ToString() == "artist")
                    {
                        ServiceManager.PlaybackController.ShuffleMode = "album";
                        replyText = "Album";
                    }
                    else if (ServiceManager.PlaybackController.ShuffleMode.ToString() == "album")
                    {
                        ServiceManager.PlaybackController.ShuffleMode = "rating";
                        replyText = "Rating";
                    }
                    else if (ServiceManager.PlaybackController.ShuffleMode.ToString() == "rating")
                    {
                        ServiceManager.PlaybackController.ShuffleMode = "score";
                        replyText = "Score";
                    }
                    else
                    {
                        ServiceManager.PlaybackController.ShuffleMode = "off";
                        replyText = "off";
                    }
                    replyReq = true;
                    break;

                case "repeat":
                    if (ServiceManager.PlaybackController.RepeatMode == PlaybackRepeatMode.None)
                    {
                        ServiceManager.PlaybackController.RepeatMode = PlaybackRepeatMode.RepeatAll;
                        replyText = "all";
                    }
                    else if (ServiceManager.PlaybackController.RepeatMode == PlaybackRepeatMode.RepeatAll)
                    {
                        ServiceManager.PlaybackController.RepeatMode = PlaybackRepeatMode.RepeatSingle;
                        replyText = "single";
                    }
                    else
                    {
                        ServiceManager.PlaybackController.RepeatMode = PlaybackRepeatMode.None;
                        replyText = "off";
                    }
                    replyReq = true;
                    break;

                case "all":
                    replyText  = ServiceManager.PlayerEngine.CurrentState.ToString().ToLower() + sep;
                    replyText += currTrack.DisplayAlbumTitle.Replace('/', '\\') + sep;
                    replyText += currTrack.DisplayArtistName.Replace('/', '\\') + sep;
                    replyText += currTrack.DisplayTrackTitle.Replace('/', '\\') + sep;
                    replyText += ((uint)(ServiceManager.PlayerEngine.Position / 1000)).ToString() + sep;
                    replyText += ((uint)(currTrack.Duration.TotalSeconds)).ToString() + sep;
                    replyText += coverExists(coverPath);
                    replyReq   = true;
                    break;

                case "test":
                    replyText = "";
                    replyReq  = true;
                    break;

                default:
                    replyText = "";
                    replyReq  = false;
                    break;
                }

                byte[] messageByte = System.Text.Encoding.UTF8.GetBytes(replyText);

                if (replyReq)
                {
                    reply(client, messageByte);
                }
                client.Close();
            }
            catch (Exception)
            {
            }
        }
Esempio n. 23
0
 public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback,
                          object state)
 {
     _remote?.BeginReceive(buffer, offset, size, socketFlags, callback, state);
 }
Esempio n. 24
0
 public IAsyncResult BeginReceive(byte[] buffer, int offset, int bufferSize, SocketFlags socketFlags, AsyncCallback callback,
                                  object state)
 {
     return(_socket.BeginReceive(buffer, offset, bufferSize, socketFlags, callback, state));
 }
Esempio n. 25
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                StateObject state  = (StateObject)ar.AsyncState;
                Socket      client = state.WorkSocket;

                // this method can be called from the middle of a .Disconnect() call
                // test with Debug > Exception > CLR exs on
                if (!client.Connected)
                {
                    return;
                }

                int bytesRead = client.EndReceive(ar);

                if (state.Buffer[7] == 0x02)
                {
                    SendAcknowledgePacket(Helpers.Bytes2String(new[] { state.Buffer[8] }));
                    OnBattlEyeMessage(Helpers.Bytes2String(state.Buffer, 9, bytesRead - 9), 256);
                }
                else if (state.Buffer[7] == 0x01)
                {
                    if (bytesRead > 9)
                    {
                        if (state.Buffer[7] == 0x01 && state.Buffer[9] == 0x00)
                        {
                            if (state.Buffer[11] == 0)
                            {
                                state.PacketsTodo = state.Buffer[10];
                            }

                            if (state.PacketsTodo > 0)
                            {
                                state.Message.Append(Helpers.Bytes2String(state.Buffer, 12, bytesRead - 12));
                                state.PacketsTodo--;
                            }

                            if (state.PacketsTodo == 0)
                            {
                                OnBattlEyeMessage(state.Message.ToString(), state.Buffer[8]);
                                state.Message     = new StringBuilder();
                                state.PacketsTodo = 0;
                            }
                        }
                        else
                        {
                            // Temporary fix to avoid infinite loops with multi-packet server messages
                            state.Message     = new StringBuilder();
                            state.PacketsTodo = 0;

                            OnBattlEyeMessage(Helpers.Bytes2String(state.Buffer, 9, bytesRead - 9), state.Buffer[8]);
                        }
                    }

                    if (_packetQueue.ContainsKey(state.Buffer[8]) && state.PacketsTodo == 0)
                    {
                        _packetQueue.Remove(state.Buffer[8]);
                    }
                }

                _packetReceived = DateTime.Now;

                client.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, state);
            }
            catch
            {
                // do nothing
            }
        }
Esempio n. 26
0
        private void EndReceive(IAsyncResult asyncResult)
        {
            var state     = (SocketObject)asyncResult.AsyncState;
            var bytesRead = m_Socket?.EndReceive(asyncResult);

            if (!bytesRead.HasValue || (bytesRead.Value == 0))
            {
                HandleDisconnect();
                return;
            }


            var raw = new byte[bytesRead.Value];

            Buffer.BlockCopy(state.Buffer, 0, raw, 0, bytesRead.Value);
            m_Buffer = m_Buffer.Append(raw);

            // If this is an IAC request, don't bother processing it or sending it back in an echo
            if (HandleIac())
            {
                m_Socket?.BeginReceive(state.Buffer, 0, state.BufferSize, SocketFlags.None, EndReceive, state);
                return;
            }

            if (m_IsEchoEnabled)
            {
                var echoed = new byte[raw.Length];
                Buffer.BlockCopy(raw, 0, echoed, 0, raw.Length);
                echoed = echoed.ExpandBackspaces();

                if (m_MaskNextInput)
                {
                    for (var i = 0; i < echoed.Length; i++)
                    {
                        if (echoed[i] == 13)
                        {
                            continue;
                        }

                        if (echoed[i] == 10)
                        {
                            continue;
                        }

                        if (echoed[i] == 8)
                        {
                            continue;
                        }

                        if (echoed[i] == 32)
                        {
                            continue;
                        }

                        echoed[i] = 42; // *
                    }
                }

                Send(echoed);
            }
            m_Buffer = m_Buffer.RemoveBackspaces();
            ProcessBuffer();
            m_Socket?.BeginReceive(state.Buffer, 0, state.BufferSize, SocketFlags.None, EndReceive, state);
        }
Esempio n. 27
0
        private void InternalBeginReceive()
        {
            m_AsyncState |= AsyncState.Pending;

            m_Socket.BeginReceive(m_RecvBuffer, 0, m_RecvBuffer.Length, SocketFlags.None, m_OnReceive, m_Socket);
        }
Esempio n. 28
0
        /// <summary>
        /// async receive data from server
        /// </summary>
        /// <param name="socket"></param>
        private void startReceive(Socket socket, int code)
        {
            byte[] data = new byte[1024];
            try
            {
                socket.BeginReceive(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    try
                    {
                        int length = socket.EndReceive(asyncResult);
                        Console.WriteLine("{0} bytes received", length);
                        byte[] receivedData = data.Take(length).ToArray();
                        // inform ui what next information will be
                        if (code == 1)
                        {
                            Hello m = new Hello();
                            m.MergeFrom(receivedData);
                            code = (int)m.Code;
                            // if received hello with code 4, means cards are distributed successfully. update ui then
                            if (code == 4)
                            {
                                this.seat = 0;
                                Console.WriteLine("card updated");
                                for (int i = 0; i < 4; i++)
                                {
                                    updateCardUI(i);    // update all
                                }
                                for (int i = 0; i < 4; i++)
                                {
                                    showCardInHand(i);
                                }
                                code = 1;
                                this.Dispatcher.Invoke(new Action(delegate
                                {
                                    this.WaitAnimation = true;
                                    if (!this.watching)
                                    {
                                        this.watcherTimer.Start(); // when playing with models, start watcherTimer, to send continue message automatically
                                    }
                                    this.score = 0;                // reset score
                                    this.round = 0;                // reset round
                                    updateScoreLabel();
                                }));
                            }
                            sendContinue();
                        }
                        // receive gamestate
                        // ui will receive this only when the watcher is not playing, i.e. is watching, or at the beginning of a game when watching
                        else if (code == 2)
                        {
                            GameState m = new GameState();
                            m.MergeFrom(receivedData);
                            code       = 1;
                            int who    = (int)m.Who;
                            int toplay = (int)m.TableID;
                            if (toplay == 0)
                            {
                                for (int i = 0; i < 13; i++)
                                {
                                    if (i < m.Hand.Count)
                                    {
                                        this.Card[who, i, 0] = (int)m.Hand[i].Suit;
                                        this.Card[who, i, 1] = (int)m.Hand[i].Rank;
                                        this.inhand[who, i]  = true;
                                    }
                                    else
                                    {
                                        this.Card[who, i, 0] = -1;
                                        this.Card[who, i, 1] = -1;
                                        this.inhand[who, i]  = false;
                                    }
                                }
                                Console.WriteLine("{0} card received", who);
                                sendContinue();
                            }
                            else
                            {
                                for (int i = 0; i < 13; i++)
                                {
                                    for (int j = 0; j < m.ValidPlays.Count; j++)
                                    {
                                        if (this.Card[who, i, 0] == (int)m.ValidPlays[j].Suit && this.Card[who, i, 1] == (int)m.ValidPlays[j].Rank)
                                        {
                                            this.Dispatcher.Invoke(new Action(delegate
                                            {
                                                this.CardUI[who, i].MouseDoubleClick += selectCard;
                                            }));
                                            break;
                                        }
                                    }
                                }
                                this.Dispatcher.Invoke(new Action(delegate
                                {
                                    this.ContinueButton.Click -= Button_Click_1;
                                    if (who == 0)
                                    {
                                        this.tipsLabel.Content = "Your Turn!\nDeclarer";
                                    }
                                    else
                                    {
                                        this.tipsLabel.Content = "Your Turn!\nDummy";
                                    }
                                }));
                            }
                        }
                        // receive play message
                        // add count -> when count reaches 4, means 1 round is over, clear desk
                        // when watching, once a round is over, do not use watcher timer to continue but use continue button only. in other cases, just set the watchertimer to 2s
                        // when playing(!watching), once a round is over, keep the desk for a while(2s or 3s). in other cases, set the watcher to 500ms
                        else if (code == 3)
                        {
                            Play m = new Play();
                            m.MergeFrom(receivedData);
                            this.count += 1;

                            code           = 1;
                            int who        = (int)m.Who;
                            Card card      = m.Card;
                            CardControl sc = null;
                            for (int i = 0; i < 13; i++)
                            {
                                if (this.Card[who, i, 0] == (int)card.Suit && this.Card[who, i, 1] == (int)card.Rank)
                                {
                                    sc = this.CardUI[(4 + who - this.seat) % 4, i];
                                    this.Dispatcher.Invoke(new Action(delegate
                                    {
                                        sc.Suit   = Encode2Suit(this.Card[who, i, 0]);
                                        sc.Number = Encode2Number(this.Card[who, i, 1]);
                                    }));
                                    this.inhand[who, i] = false;
                                    cardOut(sc);
                                    break;
                                }
                            }
                            if (this.count == 4)
                            {
                                this.count     = 0;
                                this.round    += 1;
                                this.needClear = true;
                            }
                            // when there will be button
                            // when only watching, there will always be a button
                            // when playing, only when 13 rounds is finished, there will be a continue button
                            if (this.watching || this.round == 13)
                            {
                                this.WaitAnimation = true;
                                this.Dispatcher.Invoke(new Action(delegate
                                {
                                    this.ContinueButton.Visibility = Visibility.Visible;
                                }));
                            }
                            if (!this.needClear)
                            {
                                if (this.watching)
                                {
                                    this.watcherTimer.Interval = 2000;
                                }
                                else
                                {
                                    this.watcherTimer.Interval = 500;
                                }
                                this.watcherTimer.Start();
                            }
                            else if (!this.watching && this.needClear && this.round < 13)
                            {
                                this.watcherTimer.Interval = 2000;
                                this.watcherTimer.Start();
                            }

                            int score = (int)m.Score;
                            this.Dispatcher.Invoke(new Action(delegate
                            {
                                Console.WriteLine("score:{0}", score);
                                this.score = score;
                                updateScoreLabel();
                            }));
                        }
                        else if (code == 5)
                        {
                            Console.WriteLine("received restart ok signal");
                            code = 1;
                        }
                        startReceive(socket, code);
                    }
                    catch (Exception ex)
                    {
                    }
                }, null);
            }
            catch (Exception ex)
            {
            }
        }
 public void SetupRecieveCallback(Socket sock)
 {
     try
     {
         AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
         sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
     }
     catch (Exception)
     {
     }
 }
    private static void Receive( Socket client )
    {
        try
        {

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

            client.BeginReceive ( state.buffer, 0, StateObject.bufferSize, 0, new AsyncCallback ( ClientReceiveCallback ), state );
        } catch ( Exception error )
        {

            UnityEngine.Debug.LogError ( error );
        }
    }
Esempio n. 31
0
        //<summary>
        // Once the data has been recieved from the socket this is ran.
        //</summary>
        private static void ReceiveCallBack(IAsyncResult ar)
        {
            threadList.Add(Thread.CurrentThread);

            byte[] key           = { 5, 9, 0, 4 };
            int    messageSize   = 0;
            int    messageOffset = 0;

            byte[] currentMessage;

            try{
                if (isConnected())
                {
                    StateObject state  = (StateObject)ar.AsyncState;
                    Socket      client = state.workSocket;

                    int buffSize = client.EndReceive(ar);

                    do
                    {
                        if (buffSize != 0 || fullMessage.Length != 0)
                        {
                            if (fullMessage.Length != 0 && buffSize != 0)
                            {
                                Array.Resize(ref fullMessage, fullMessage.Length + buffSize);
                                byte[] newMessage = new byte[buffSize];
                                newMessage = AltimitArray.copyOfRange(state.buffer, 0, buffSize);
                                Array.ConstrainedCopy(newMessage, 0, fullMessage, fullMessageSize, newMessage.Length);
                                messageSize = 0;
                            }
                            else if (buffSize != 0)
                            {
                                fullMessage = new byte[buffSize];
                                fullMessage = AltimitArray.copyOfRange(state.buffer, 0, buffSize);
                                messageSize = 0;
                            }
                            else if (fullMessage.Length != 0)
                            {
                                messageSize = 0;
                            }

                            if (messageSize == 0 && fullMessage.Length >= 4)
                            {
                                messageSize = AltimitConverter.convertToInt(AltimitArray.copyOfRange(fullMessage, 0, 4));
                                if (messageSize <= fullMessage.Length)
                                {
                                    byte[] messageKey = AltimitArray.copyOfRange(fullMessage, messageSize - 4, messageSize);
                                    if (key.SequenceEqual(messageKey))
                                    {
                                        currentMessage = new byte[messageSize - 8];
                                        messageOffset  = 4;
                                        Array.ConstrainedCopy(fullMessage, messageOffset, currentMessage, 0, currentMessage.Length);
                                        messageOffset = messageSize;

                                        new Thread(() =>
                                        {
                                            List <object> sentMessage = AltimitConverter.ReceiveConversion(currentMessage);
                                            InvokeMessage(sentMessage);
                                        }).Start();

                                        fullMessage     = AltimitArray.copyOfRange(fullMessage, messageOffset, fullMessage.Length);
                                        fullMessageSize = fullMessage.Length;

                                        buffSize = 0;
                                    }
                                    else
                                    {
                                        Debug.Log("Key was not found. Message will try to be completed in next read!");
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                    }while(fullMessage.Length > 0);

                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
                }
                else
                {
                    Disconnect();
                    return;
                }
            } catch (Exception e) {
                Debug.LogError(e.ToString());
                Disconnect();
                return;
            }
        }
Esempio n. 32
0
 private static void Receive(Socket client)
 {
     try
     {
         StateObject state = new StateObject { WorkSocket = client };
         client.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, state);
     }
     catch (Exception e)
     {
         throw;
     }
 }
 public Listener(Socket s, Messenger mesenger_ref)
 {
     sock = s;
     mesenger = mesenger_ref;
     sock.BeginReceive(new byte[] { 0 }, 0, 0, 0, callback, null);
 }
Esempio n. 34
0
        /// <summary>
        /// Handles all incoming data from the game server.
        /// </summary>
        /// <param name="ar">
        /// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
        /// </param>
        private void BeginReceiveServerCallback(IAsyncResult ar)
        {
            try
            {
                if (_serverSocket == null)
                {
                    return;
                }

                var count = _serverSocket.EndReceive(ar);
                if (count <= 0)
                {
                    ResetConnection();
                    return;
                }

                _serverInMessage.Size = (uint)BitConverter.ToUInt16(_serverInMessage.GetBuffer(), 0) + 2;
                while (count < _serverInMessage.Size)
                {
                    var read = _serverSocket.Receive(_serverInMessage.GetBuffer(), count, (int)(_serverInMessage.Size - count), SocketFlags.None);
                    if (read <= 0)
                    {
                        throw new Exception("[Connection.BeginReceiveServerCallback] Server connection broken.");
                    }

                    count += read;
                }

                if (IsServerPacketDecryptionEnabled)
                {
                    _serverInMessage.PrepareToParse(_xteaKey, _zStream);
                    OnReceivedServerMessage?.Invoke(_serverInMessage.GetData());
                }

                if (IsServerPacketParsingEnabled)
                {
                    _serverOutMessage.Reset();
                    _serverOutMessage.SequenceNumber = _serverInMessage.SequenceNumber;

                    ParseServerMessage(_client, _serverInMessage, _serverOutMessage);

                    if (IsServerPacketModificationEnabled && _client.Logger.Level == Logger.LogLevel.Debug)
                    {
                        _client.Logger.Debug($"In Size: {_serverInMessage.Size}, Out Size: {_serverOutMessage.Size}");
                        _client.Logger.Debug($"In Data: {BitConverter.ToString(_serverInMessage.GetData()).Replace('-', ' ')}");
                        _client.Logger.Debug($"Out Data: {BitConverter.ToString(_serverOutMessage.GetData()).Replace('-', ' ')}");
                    }

                    SendToClient(IsServerPacketModificationEnabled ? _serverOutMessage : _serverInMessage);
                }
                else
                {
                    if (IsServerPacketDecryptionEnabled)
                    {
                        _serverInMessage.PrepareToSend(_xteaKey, IsServerPacketCompressionEnabled ? _zStream : null);
                    }
                    SendToClient(_serverInMessage.GetData());
                }

                _serverSocket.BeginReceive(_serverInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveServerCallback), 1);
            }
            catch (ObjectDisposedException)
            {
                // This exception can occur if Stop() is called.
            }
            catch (SocketException)
            {
                // This exception can happen if the server, forcefully, closes the connection.
                ResetConnection();
            }
            catch (Exception ex)
            {
                _client.Logger.Error(ex.ToString());
                _client.Logger.Error($"Data: {BitConverter.ToString(_serverInMessage.GetData()).Replace('-', ' ')}");
            }
        }
Esempio n. 35
0
 public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     return(_socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state));
 }
Esempio n. 36
0
 /// <summary>
 /// Setup the callback for recieved data and loss of conneciton
 /// </summary>
 public void SetupRecieveCallback(Socket sock)
 {
     try
     {
         AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
         sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
     }
     catch (Exception ex)
     {
         m_Errors("Setup Recieve Callback failed!:" + ex.ToString());
     }
 }
Esempio n. 37
0
        private void ParseFirstClientMessage()
        {
#if DEBUG_PROXY
            Trace.WriteLine("[DEBUG] Proxy [ParseFirstClientMessage]");
#endif

            clientInMessage.ReadPosition = 2;
            clientInMessage.Encrypted    = false;

            if (Adler.Generate(clientInMessage) != clientInMessage.ReadUInt())
            {
                throw new Exception("Wrong checksum.");
            }

            byte protocolId = clientInMessage.ReadByte();

            if (protocolId == 0x01)             //Login
            {
                protocol = Protocol.Login;
                ushort clientType      = clientInMessage.ReadUShort();
                ushort protocolVersion = clientInMessage.ReadUShort();

                if (client.Version.Number >= ClientVersion.VVersion10000.Number)
                {
                    uint clientVersion = clientInMessage.ReadUInt();
                }

                uint datSignature = clientInMessage.ReadUInt();
                uint sprSignature = clientInMessage.ReadUInt();
                uint picSignature = clientInMessage.ReadUInt();

                if (client.Version.Number >= ClientVersion.Version10000.Number)
                {
                    byte clientPreviewState = clientInMessage.ReadByte();
                }

                Rsa.OpenTibiaDecrypt(clientInMessage);

                //TRACKE OTSERVER UPDATE
                if (client.Version.Number >= ClientVersion.Version1073.Number)
                {
                    int tempPos = clientInMessage.ReadPosition;
                    clientInMessage.ReadPosition = clientInMessage.Size - 128;
                    Rsa.OpenTibiaDecrypt(clientInMessage);
                    clientInMessage.ReadPosition = tempPos;
                }

                Array.Copy(clientInMessage.Buffer, serverOutMessage.Buffer, clientInMessage.Size);
                serverOutMessage.Size          = clientInMessage.Size;
                serverOutMessage.WritePosition = clientInMessage.ReadPosition - 1; //the first byte is zero

                xteaKey    = new uint[4];
                xteaKey[0] = clientInMessage.ReadUInt();
                xteaKey[1] = clientInMessage.ReadUInt();
                xteaKey[2] = clientInMessage.ReadUInt();
                xteaKey[3] = clientInMessage.ReadUInt();

                var acc  = clientInMessage.ReadString();                //account name
                var pass = clientInMessage.ReadString();                //password

                if (client.IsOpenTibiaServer)
                {
                    Rsa.OpenTibiaEncrypt(serverOutMessage);
                    //TRACKE OTSERVER UPDATE
                    if (client.Version.Number >= ClientVersion.Version10000.Number)
                    {
                        serverOutMessage.WritePosition = serverOutMessage.Size - 128;
                        Rsa.OpenTibiaEncrypt(serverOutMessage);
                    }
                }
                else
                {
                    Rsa.RealTibiaEncrypt(serverOutMessage);
                    if (client.Version.Number >= ClientVersion.Version10000.Number)
                    {
                        serverOutMessage.WritePosition = serverOutMessage.Size - 128;
                        Rsa.RealTibiaEncrypt(serverOutMessage);
                    }
                }

                Adler.Generate(serverOutMessage, true);
                serverOutMessage.WriteHead();

                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Connect(loginServers[0].Server, loginServers[0].Port);

                serverSocket.Send(serverOutMessage.Buffer, 0, serverOutMessage.Size, SocketFlags.None);

                serverInMessage.Reset();
                serverSocket.BeginReceive(serverInMessage.Buffer, 0, 2, SocketFlags.None, ServerReceiveCallback, null);
            }
            else if (protocolId == 0x0A)             //Game
            {
                protocol = Protocol.World;

                ushort clientType      = clientInMessage.ReadUShort();
                ushort protocolVersion = clientInMessage.ReadUShort();

                if (client.Version.Number >= ClientVersion.Version10000.Number)
                {
                    uint   clientVersion   = clientInMessage.ReadUInt();
                    ushort contentRevision = 0;
                    if (client.Version.Number >= ClientVersion.Version1071.Number)
                    {
                        contentRevision = clientInMessage.ReadUShort();
                    }
                    byte clientPreviewState = clientInMessage.ReadByte();
                }

                Rsa.OpenTibiaDecrypt(clientInMessage);

                Array.Copy(clientInMessage.Buffer, serverOutMessage.Buffer, clientInMessage.Size);
                serverOutMessage.Size          = clientInMessage.Size;
                serverOutMessage.WritePosition = clientInMessage.ReadPosition - 1;                 //the first byte is zero

                xteaKey    = new uint[4];
                xteaKey[0] = clientInMessage.ReadUInt();
                xteaKey[1] = clientInMessage.ReadUInt();
                xteaKey[2] = clientInMessage.ReadUInt();
                xteaKey[3] = clientInMessage.ReadUInt();

                clientInMessage.ReadByte();

                //var accountName = clientInMessage.ReadString();
                var sessionKey    = clientInMessage.ReadString();
                var characterName = clientInMessage.ReadString();
                //var password = clientInMessage.ReadString();

                if (client.IsOpenTibiaServer)
                {
                    Rsa.OpenTibiaEncrypt(serverOutMessage);
                }
                else
                {
                    Rsa.RealTibiaEncrypt(serverOutMessage);
                }

                Adler.Generate(serverOutMessage, true);
                serverOutMessage.WriteHead();

                serverSocket.Send(serverOutMessage.Buffer, 0, serverOutMessage.Size, SocketFlags.None);
            }
            else
            {
                throw new Exception("Invalid protocol " + protocolId.ToString("X2"));
            }
        }
Esempio n. 38
0
    // Use this for initialization
    void Start()
    {
        guiConsole = GameObject.Find("Console").guiText;

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

             sock.Connect( "localhost", 1337 );
             if( sock.Connected )
             {
                     ConsoleMessage( "Connected" );

                     sock.BeginReceive(
                         recvBuffer,
                         0,
                         recvBuffer.Length,
                         SocketFlags.None,
                         new AsyncCallback( ReceiveComplete ),
                         null );
             }
             else
             {
                     ConsoleMessage( "Fail to connect" );
             }
    }
Esempio n. 39
0
 private void Receive(Socket client)
 {
     try
     {
         client.BeginReceive(stateObj.buffer, 0, stateObj.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), stateObj);
     }
     catch (Exception e)
     {
         Debug.Log(e.ToString());
     }
 }
Esempio n. 40
0
        private void ReceiveData(IAsyncResult result)
        {
            try
            {
                Socket?clientSocket  = (Socket?)result.AsyncState; // Socket may be closed/disposed.
                int    bytesReceived = clientSocket?.Connected ?? false?clientSocket?.EndReceive(result) ?? 0 : 0;

                if (bytesReceived == 0)
                {
                    CloseSocket(clientSocket);
                    m_serverSocket.BeginAccept(new AsyncCallback(HandleIncomingConnection), m_serverSocket);
                }
                else if (m_data[0] < 0xF0)
                {
                    ClientModel?client       = GetClientBySocket(clientSocket);
                    string      receivedData = client !.ReceivedData;

                    // 0x2E = '.', 0x0D = carriage return, 0x0A = new line
                    if ((m_data[0] == 0x2E && m_data[1] == 0x0D && receivedData.Length == 0) || (m_data[0] == 0x0D && m_data[1] == 0x0A))
                    {
                        //sendMessageToSocket(clientSocket, "\u001B[1J\u001B[H");
                        MessageReceived(this, new MessageReceivedEventArgs {
                            ClientInstance = client, ReceivedData = client.ReceivedData
                        });
                        client.ReceivedData = string.Empty;
                    }
                    else
                    {
                        if (m_data[0] == 0x08) // 0x08 => backspace character
                        {
                            if (receivedData.Length > 0)
                            {
                                client.RemoveLastCharacterReceived();
                                SendBytesToSocket(clientSocket, new byte[] { 0x08, 0x20, 0x08 });
                            }
                            else
                            {
                                clientSocket?.BeginReceive(m_data, 0, m_dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
                            }
                        }
                        else if (m_data[0] == 0x7F) // 0x7F => delete character
                        {
                            clientSocket?.BeginReceive(m_data, 0, m_dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
                        }
                        else
                        {
                            client.AppendReceivedData(Encoding.ASCII.GetString(m_data, 0, bytesReceived));

                            // Echo back the received character if client is not typing a password.
                            if (client.CurrentStatus != CLIENT_STATUS.AUTHENTICATING)
                            {
                                SendBytesToSocket(clientSocket, new byte[] { m_data[0] });
                            }
                            else // Echo back asterisks if client is typing a password.
                            {
                                SendMessageToSocket(clientSocket, "*");
                            }

                            clientSocket?.BeginReceive(m_data, 0, m_dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
                        }
                    }
                }
                else
                {
                    clientSocket?.BeginReceive(m_data, 0, m_dataSize, SocketFlags.None, new AsyncCallback(ReceiveData), clientSocket);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
        }
Esempio n. 41
0
 private void Receive(Socket client)
 {
     try
     {
         StateObject state = new StateObject();
         state.socket = client;
         client.BeginReceive(state.buffer, 0, StateObject.buffSize, 0, new AsyncCallback(ReceiveCallback), state);
     }
     catch (Exception e)
     {
         LogsSystem.Instance.Print(e.ToString(), LogLevel.ERROR);
     }
 }
    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            distributor.closeConnection();
        }
    }
Esempio n. 43
0
 private void OnSocketConnect(System.IAsyncResult ar)
 {
     Debug.Log("Wow! Such Connection!");
     YourSocket = MySocket.EndAccept(ar);
     YourSocket.BeginReceive(this.SocketBuffer,
                             0,
                             this.SocketBuffer.Length,
                             SocketFlags.None,
                             this.OnSocketRead,
                             null);
     this.LocalPlayer[0] = true;
     this.LocalPlayer[1] = false;
     this.IsConnected = true;
 }
Esempio n. 44
0
        private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;
            int    received;

            try
            {
                received = current.EndReceive(AR);
            }
            catch (SocketException)
            {
                Console.WriteLine("Client forcefully disconnected");
                // Don't shutdown because the socket may be disposed and its disconnected anyway.
                current.Close();
                clientSockets.Remove(current);
                return;
            }

            /* seriallize sample
             * byte[] dataBuffer = buffer; ;
             * BinaryFormatter bin = new BinaryFormatter();
             * MemoryStream mem = new MemoryStream();
             * mem.Write(dataBuffer, 0, dataBuffer.Length);
             * mem.Seek(0, 0);
             * NetPacket np = (NetPacket)bin.Deserialize(mem);
             */

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

            Console.WriteLine("Received Text: " + text);

            if (text.ToLower() == "get time") // Client requested time
            {
                Console.WriteLine("Text is a get time request");
                byte[] data = Encoding.ASCII.GetBytes(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                current.Send(data);
                Console.WriteLine("Time sent to client");
            }
            else if (text.ToLower() == "exit") // Client wants to exit gracefully
            {
                // Always Shutdown before closing
                current.Shutdown(SocketShutdown.Both);
                current.Close();
                clientSockets.Remove(current);
                Console.WriteLine("Client disconnected");
                return;
            }
            else if (text.ToLower() == "all") // Client wants to exit gracefully
            {
                Console.WriteLine("All Publish");

                foreach (Socket socket in clientSockets)
                {
                    byte[] data = Encoding.ASCII.GetBytes("Hi member?");

                    if (socket != current)
                    {
                        socket.Send(data);
                    }
                }
            }
            else
            {
                Console.WriteLine("Text is an invalid request");
                byte[] data = Encoding.ASCII.GetBytes("Invalid request");
                current.Send(data);
                Console.WriteLine("Warning Sent");
            }

            current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
        }
 //Receives the message and uses ReceiveCallback
 private void Receive(Socket client)
 {
     try
     {
         StateObject state = new StateObject(); // Create the state object.
         state.workSocket = client;
         client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         log.Debug(ex.ToString());
     }
 }
Esempio n. 46
0
 public void StartClient()
 {
     socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
 }
Esempio n. 47
0
        private async void Receive()
        {
            var state = new StateObject {
                WorkSocket = _socket
            };

            _disconnectionType = null;

            _socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, state);

            while (_socket.Connected && _keepRunning)
            {
                int timeoutClient = (int)(DateTime.Now - _packetSent).TotalSeconds;
                int timeoutServer = (int)(DateTime.Now - _packetReceived).TotalSeconds;

                if (timeoutClient >= 5)
                {
                    if (timeoutServer >= 20)
                    {
                        Disconnect(BattlEyeDisconnectionType.ConnectionLost);
                        _keepRunning = true;
                    }
                    else
                    {
                        if (_packetQueue.Count == 0)
                        {
                            SendCommandPacket(null, false);
                        }
                    }
                }

                if (_socket.Connected && _packetQueue.Count > 0 && _socket.Available == 0)
                {
                    try
                    {
                        int key = _packetQueue.First().Key;

                        if (_currentPacket == -1 || !_packetQueue.ContainsKey(_currentPacket))
                        {
                            _currentPacket = key;
                            string value = _packetQueue[key][0];
                            SendPacket(ConstructPacket(BattlEyePacketType.Command, key, value));
                        }
                    }
                    catch
                    {
                        // Prevent possible crash when packet is received at the same moment it's trying to resend it.
                    }
                }

                await Task.Delay(250);
            }

            if (!_socket.Connected)
            {
                if (ReconnectOnPacketLoss && _keepRunning)
                {
                    Connect();
                }
                else if (!_keepRunning)
                {
                    //let the thread finish without further action
                }
                else
                {
                    OnDisconnect(_loginCredentials, BattlEyeDisconnectionType.ConnectionLost);
                }
            }
        }
Esempio n. 48
0
        public static void Receive(IAsyncResult ar = null)
        {
            if (!connected)
            {
                return;
            }

            if (ar != null)
            {
                try
                {
                    receivePosition += socket.EndReceive(ar);
                }
                catch (Exception e)
                {
                    Debug.LogWarning(e.ToString());
                }
            }

            int i = recvStream.Position;

            while (receivePosition >= i + 2)
            {
                int length = (recvStream[i] << 8) | recvStream[i + 1];

                int sz = length + 2;
                if (receivePosition < i + sz)
                {
                    break;
                }

                recvStream.Seek(2, SeekOrigin.Current);

                if (length > 0)
                {
                    byte[] data = new byte[length];
                    recvStream.Read(data, 0, length);
                    recvQueue.Enqueue(data);
                }

                i += sz;
            }

            if (receivePosition == recvStream.Buffer.Length)
            {
                recvStream.Seek(0, SeekOrigin.End);
                recvStream.MoveUp(i, i);
                receivePosition = recvStream.Position;
                recvStream.Seek(0, SeekOrigin.Begin);
            }

            try
            {
                socket.BeginReceive(recvStream.Buffer, receivePosition,
                                    recvStream.Buffer.Length - receivePosition,
                                    SocketFlags.None, receiveCallback, socket);
            }
            catch (Exception e)
            {
                Debug.LogWarning(e.ToString());
            }
        }
Esempio n. 49
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. 50
0
        // BeginReceive()'s call back fucntion
        public void CallBack_ReceiveMsg(IAsyncResult ar)
        {
            int      length;
            String   MsgRecvStr = null;
            CheckHub a          = new CheckHub();

            try
            {
                // If the socket close, return the 0 value
                length = clientsock.EndReceive(ar);

                if (length > 0)
                {
                    MsgRecvStr = Encoding.Default.GetString(MsgRecvBuff, 0, length);

                    Console.WriteLine("Dato recibido:" + MsgRecvStr + "\n");


                    //Seteo la temperatura
                    a.SetTemp(MsgRecvStr);

                    //Guardo en base de datos los registros
                    dbcon.Open();

                    IDbCommand dbcmd = dbcon.CreateCommand();

                    /*sql =
                     * "SELECT temperatura, humedad " +
                     * "FROM registros";*/
                    sql_aux = MsgRecvStr.Split(' ');
                    sql     = "INSERT INTO registros (fecha,temperatura,humedad,luminosidad,voltspanel,voltsbateria)" +
                              "VALUES('" + DateTime.Now.ToString() + "'," + sql_aux[0] + "," + sql_aux[1] + "," + sql_aux[2] + "," + sql_aux[3] + "," + 0 + ")";
                    dbcmd.CommandText = sql;
                    IDataReader reader = dbcmd.ExecuteReader();

                    /*while (reader.Read())
                     * {
                     *  string temperatura = reader.GetFloat(0).ToString();
                     *  string humedad = reader.GetFloat(1).ToString();
                     *  Console.WriteLine("Valores: {0} {1}",
                     *      temperatura, humedad);
                     * }*/
                    // clean up
                    reader.Dispose();
                    dbcmd.Dispose();
                    dbcon.Close();


                    // The socket can continuedly wait the receive message because of this function
                    clientsock.BeginReceive(MsgRecvBuff, 0, MsgRecvBuff.Length, SocketFlags.None, new AsyncCallback(CallBack_ReceiveMsg), clientsock);
                }
                else
                {
                    // If the socket close, return the 0 value
                    // Then, socket close.
                    clientsock.Close();
                }
            }
            catch (Exception er)
            {
                Console.WriteLine(er.Message);
            }
        }
Esempio n. 51
0
        private void ClientBeginAcceptCallback(IAsyncResult ar)
        {
            try
            {
                lock (this)
                {
                    if (!accepting)
                    {
                        return;
                    }

#if DEBUG_PROXY
                    Trace.WriteLine("[DEBUG] Proxy [ClientBeginAcceptCallback]");
#endif

                    if (loginClientSocket == null || worldClientSocket == null)
                    {
                        return;
                    }

                    accepting = false;

                    Protocol protocol = (Protocol)ar.AsyncState;
                    clientSocket = null;

                    if (protocol == Protocol.Login)
                    {
                        clientSocket = loginClientSocket.EndAccept(ar);
                    }
                    else
                    {
                        clientSocket = worldClientSocket.EndAccept(ar);

                        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        CharacterLoginInfo selectedChar = charList[client.SelectedChar];

                        if (client.Version.Number == ClientVersion.Version1011.Number)
                        {
                            if (selectedChar.WorldIP == 0)
                            {
                                serverSocket.Connect(new IPEndPoint(Dns.GetHostAddresses("game.tibia.ciproxy.com")[0], selectedChar.WorldPort));
                            }
                            else
                            {
                                serverSocket.Connect(new IPEndPoint(selectedChar.WorldIP, selectedChar.WorldPort));
                            }
                        }
                        else
                        {
                            serverSocket.Connect(new IPEndPoint(selectedChar.WorldIP, selectedChar.WorldPort));
                        }

                        serverInMessage.Reset();
                        serverSocket.BeginReceive(serverInMessage.Buffer, 0, 2, SocketFlags.None, ServerReceiveCallback, null);
                    }

                    clientSocket.LingerState = new LingerOption(true, 2);

                    loginClientSocket.Close();
                    worldClientSocket.Close();

                    loginClientSocket = null;
                    worldClientSocket = null;

                    clientInMessage.Reset();
                    clientSocket.BeginReceive(clientInMessage.Buffer, 0, 2, SocketFlags.None, ClientReceiveCallback, null);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("[Error] Proxy [ClientBeginAcceptCallback]: " + ex.Message);
            }
        }
Esempio n. 52
0
 private void AcceptReceiveCallback(IAsyncResult ar)
 {
     listener   = (Socket)ar.AsyncState;
     ClientSock = listener.EndAccept(ar);
     ClientSock.BeginReceive(MsgRecvBuff, 0, MsgRecvBuff.Length, SocketFlags.None, new AsyncCallback(CallBack_ReceiveMsg), ClientSock);
 }
 public CommanderTcpClient(Socket clientSocket)
 {
     _clientSocket = clientSocket;
     _clientSocket.BeginReceive(ReceiveBuffer, SocketFlags.None, Received, _clientSocket);
 }