예제 #1
0
        private static void ClientConnectCallback(IAsyncResult result)
        {
            try
            {
                _clientSocket.EndConnect(result);
                if (_clientSocket.Connected == false)
                {
                    return;
                }
                else
                {
                    _clientSocket.NoDelay = true;
                    _clientNetworkStream  = _clientSocket.GetStream();
                    // Constants.MAX_BUFFER_SIZE is multiplied 2 is multiplied to have a much large '
                    _clientNetworkStream?.BeginRead(_asyncBuffer, Constants.NETWORK_STREAM_OFFSET, Constants.MAX_BUFFER_SIZE * 2, ReceiveCallback, null);

                    Text.WriteLine("Successfully connected to server", TextType.INFO);

                    //request for chat history
                    ChatHistory("8c731da6-b4f2-4100-8dda-10585fd32ee3");
                }
            }
            catch
            {
                Text.WriteLine("Connecting to server...", TextType.INFO);

                Thread.Sleep(10000);

                ConnectClientToServer(Constants.SERVER_IP, Constants.PORT);

                //Text.WriteLine("ClientConnectCallback error: " + ex.Message, TextType.ERROR);
            }
        }
예제 #2
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="client"></param>
 public TcpClientStream(TcpClient client)
 {
     this.Client = client;
     this.Stream = client.GetStream();
     this.Debugging = MainForm.Config.DebugStream;
     Stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(ReadCallback), Stream);
 }
예제 #3
0
파일: Server2.cs 프로젝트: jujugy/bhsc_o
        public bahaCash(TcpClient client)
        {
            //check ip address
            this.client = client;
            splitstring = client.Client.RemoteEndPoint.ToString().Split('.');
            clientip = splitstring[0] + splitstring[1] + splitstring[2];

            if (clientip == bahaip){
                string time = Util.getTime();
                Console.WriteLine("\nCorrect Connected" + time + "!{0} <-- {1}",
                    client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

                streamToClient = client.GetStream();
                buffer = new byte[BufferSize];

                handler = new RequestHandler();

                AsyncCallback callBack = new AsyncCallback(ReadComplete);
                streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null); //r
            }else{
                string time = Util.getTime();
                Console.WriteLine("\nWrong Connected" + time + "!{0} <-- {1}" + "_" + clientip,
                    client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
                client.Close();
            }
        }
        public XmlSocketIO(String address, Int32 port)
        {
            IPAddress IPAddr = IPAddress.Parse(address);
            server = new TcpListener(IPAddr, port);

            // Start listening for client requests.
            server.Start();
            Console.Write("Waiting for a connection to "+address+", port "+port+"... ");

            // Perform a blocking call to accept requests.
            // You could also user server.AcceptSocket() here.
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Connected!");

            stream = client.GetStream();
            readBuffer = new byte[256]; // maximum size of a message

            // set the function that will be called when a complete message came in
            readCallBack = new AsyncCallback(this.OnCompletedRead);

            // start asynchronous read from socket
            stream.BeginRead(
                readBuffer,             // where to put the results
                0,						// offset
                readBuffer.Length,      // how many bytes (BUFFER_SIZE)
                readCallBack,			// call back delegate
                null);					// local state object
        }
예제 #5
0
		internal HttpClient(Socket socket, HttpServer server)
		{
			this.server = server;
			this.socket = socket;
			IPEndPoint remoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
			isConnected = true;
			this.remoteAddress = remoteEndPoint.Address.ToString();
			this.remotePort = remoteEndPoint.Port;

			server.Stopping += new EventHandler(server_Stopping);

			stream = new NetworkStream(socket, true);

			try
			{
				stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReceiveData), this);
				
			}
			catch(IOException)
			{
				Disconnect();
				throw;
			}
			server.OneHertzTick += new EventHandler(server_OneHertzTick);
		}
예제 #6
0
 public void Read (AsyncCallback readCallback) 
 {
     stream = client.GetStream();
     TCPStreamState state = new TCPStreamState(stream);
     stream.BeginRead
         (state.RecvBytes, 0, state.RecvBytes.Length, readCallback, state);
 }
예제 #7
0
 private void AfterAccept(System.IAsyncResult IR)
 {
     recv = listener.EndAcceptTcpClient(IR);
     RecvStream = recv.GetStream();
     data = new byte[1024];
     RecvStream.BeginRead(data, 0, data.Length, AfterRead, null);
 }
예제 #8
0
파일: Client.cs 프로젝트: kaiss78/hustoes
 /// <summary>
 /// Client构造函数
 /// </summary>
 /// <param name="client">以连接好的Socket</param>
 public Client(TcpClient client)
 {
     #if DEBUG
     OESServer.logForm.InsertMsg("Init [Client.Client]");
     #endif
     this.client = client;
     ns = client.GetStream();
     ns.BeginRead(buffer, 0, bufferSize, new AsyncCallback(receive_callBack), client);
 }
예제 #9
0
        public Client(TcpClient c, Server s, Config.AuthConfig a)
        {
            client = c;
            server = s;
            authconfig = a;

            stream = client.GetStream();
            stream.BeginRead(read_buffer, 0, 1024, new AsyncCallback(callbackRead), this);
        }
예제 #10
0
        private Network()
        {
            client = new TcpClient();

            client.Connect(serverEndPoint);

            clientStream = client.GetStream();

            clientStream.BeginRead(ReceivedBytes, 0, 512, receiveCallback, null);
        }
예제 #11
0
        public FrostbiteLayerConnection(TcpClient acceptedConnection) {
            ReceivedBuffer = new byte[4096];
            PacketStream = null;

            Client = acceptedConnection;

            NetworkStream = Client.GetStream();

            NetworkStream.BeginRead(ReceivedBuffer, 0, ReceivedBuffer.Length, ReceiveCallback, this);
        }
        //---------------------------------------------------------------------------------------//
        // Construction, Destruction
        //---------------------------------------------------------------------------------------//
        /// <summary>
        /// Connects to remote server
        /// </summary>
        public TcpClientConnection(IPEndPoint endPoint)
        {
            Contract.Requires(endPoint != null);

            buffer = new byte[10 * 1024];
            tcpClient = new TcpClient();
            tcpClient.Connect(endPoint);
            stream = tcpClient.GetStream();
            stream.BeginRead(buffer, 0, buffer.Length, EndRead, null);
        }
예제 #13
0
        protected void RegisterWaitData()
        {
            var stream = m_Stream;

            if (stream != null)
            {
                var ptr = m_ReceiveBuffer.LockWrite(1024);
                m_Stream?.BeginRead(ptr.Ptr, ptr.Offset, ptr.Size, DataReceivedCallback, m_Stream);
            }
        }
예제 #14
0
 private void StartCallback(IAsyncResult ar)
 {
     _client = _listener.EndAcceptTcpClient(ar);
     _listener.Stop();
     _networkStream = _client.GetStream();
     if (_networkStream.CanRead)
     {
         _networkStream.BeginRead(_receiveBuffer, 0, _receiveBuffer.Length, ReceiveCallback, null);
     }
     Connected = true;
     OnPropertyChanged("ConnectionStatus");
 }
예제 #15
0
 public ClientConnection(Socket socket)
     : this()
 {
     m_Socket = socket;
     m_NetStream = new NetworkStream(m_Socket);
     try
     {
         m_NetStream.BeginRead(m_Buffer, 0, m_Buffer.Length,  new AsyncCallback(OnDataReceive), null);
     }
     catch
     {
         DisConnect();
     }
 }
예제 #16
0
파일: Client.cs 프로젝트: RudyMeijer/tcp
 private void btnConnect_Click(object sender, EventArgs e)
 {
     try
     {
         var port = int.Parse(txtPortNr.Text); //8888
         client = new TcpClient(txtHostname.Text, port);
         if (client.Connected) ShowMessage("\r\nClient is succesfull connected!");
         //client.ReceiveTimeout = 0;
         ns = client.GetStream();
         ns.BeginRead(buf, 0, 300, HandleRead, null);
     }
     catch (Exception ex)
     {
         ShowMessage("\r\n " + ex.Message);
     }
 }
예제 #17
0
 public Client(TcpClient tcpClient, Server _serv)
 {
     Joined = false;
     Entity = null;
     disconnecting = false;
     tcp = tcpClient;
     IP = (tcp.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
     NetStream = tcp.GetStream();
     Reader = new NetReader(NetStream);
     Writer = new BinaryWriter(NetStream);
     Server = _serv;
     ID = Server.CreateID();
     if (ID == 0)
         ID = Global.Config.max_players + 1;
     recvBuffer = new byte[4];
     NetStream.BeginRead(recvBuffer, 0, 4, HeadCallback, null);
 }
예제 #18
0
 public void OnConnect(IAsyncResult iar)
 {
     try {
         if (_tcp != null) {
             _tcp.EndConnect(iar);
             _stream = _tcp.GetStream();
             _stream.BeginRead(_readBuf, 0, _readBuf.Length, TcpOnDataReceived, null);
             Logger.Success("Connected TCP socket");
             if (Connected != null)
                 Connected(this, EventArgs.Empty);
         }
     }
     catch {
         Logger.Error("Couldn't connect TCP socket");
         ApplyReconnectBehavior();
     }
 }
예제 #19
0
파일: Client.cs 프로젝트: Wroud/Coob
        public Client(TcpClient tcpClient)
        {
            Joined = false;
            Entity = null;

            tcp = tcpClient;
            IP = (tcp.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
            NetStream = tcp.GetStream();
            Reader = new NetReader(NetStream);
            Writer = new BinaryWriter(NetStream);

            ID = Root.Coob.CreateID();

            if (ID == 0)
                throw new UserLimitReachedException();

            recvBuffer = new byte[4];
            NetStream.BeginRead(recvBuffer, 0, 4, idCallback, null);
        }
예제 #20
0
파일: Server2.cs 프로젝트: gy09535/redis
        public RemoteClient(TcpClient client)
        {
            this.client = client;

            // 打印连接到的客户端信息
            Console.WriteLine("\nClient Connected!{0} <-- {1}",
                client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

            // 获得流
            streamToClient = client.GetStream();
            buffer = new byte[BufferSize];

            // 设置RequestHandler
            handler = new RequestHandler();

            // 在构造函数中就开始准备读取
            AsyncCallback callBack = ReadComplete;
            streamToClient.BeginRead(buffer, 0, BufferSize, callBack, null);
        }
예제 #21
0
        private static void ReceiveCallback(IAsyncResult result)
        {
            try
            {
                int readByteSize = _clientNetworkStream.EndRead(result);
                if (readByteSize <= 0)
                {
                    return;
                }
                byte[] newBytes = new byte[readByteSize];
                Buffer.BlockCopy(_asyncBuffer, Constants.NETWORK_STREAM_OFFSET, newBytes, Constants.NETWORK_STREAM_OFFSET, readByteSize);

                ClientHandleData.HandleDataFromServer(newBytes);
                _clientNetworkStream?.BeginRead(_asyncBuffer, Constants.NETWORK_STREAM_OFFSET, Constants.MAX_BUFFER_SIZE * 2, ReceiveCallback, null);
            }
            catch
            {
                //todo: Write retry connection function
                ConnectClientToServer(Constants.SERVER_IP, Constants.PORT);
            }
        }
예제 #22
0
        private void ReceiveCallback(IAsyncResult _result)
        {
            try                                            //inside a try catch so that the server does not crash on error
            {
                int _byteLength = stream.EndRead(_result); //received data from server
                if (_byteLength <= 0)                      //if no data received, exit method
                {
                    Server.clients[id].Disconnect();
                    return;
                }

                byte[] _data = new byte[_byteLength];
                Array.Copy(receiveBuffer, _data, _byteLength);  //copy received data

                receivedData.Reset(HandleData(_data));
                stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);  //continue streaming from server
            }
            catch (Exception _ex)
            {
                Debug.Log($"Error receiving TCP data: {_ex}");
                Server.clients[id].Disconnect();
            }
        }
예제 #23
0
        protected void StreamRead(IAsyncResult ar)
        {
            try
            {
                int offset     = 0;
                int prevoffset = offset;

                int bytes = theStream.EndRead(ar);
                if (ProcessDataBuffer(bytes))
                {
                    theStream.BeginRead(DataBuffer, DataReadOffset, BUFFER_SIZE - DataReadOffset, StreamRead, this);
                }
                else
                {
                    StreamStatusEvent?.Invoke("Disconnected");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                StreamStatusEvent?.Invoke("Disconnected");
            }
        }
예제 #24
0
        public void ASyncReadResult(IAsyncResult result)
        {
            UTF8Encoding  encoding   = new UTF8Encoding();
            NetworkStream streamRead = (NetworkStream)result.AsyncState;

            if (result == null)
            {
                return;
            }
            string text = String.Empty;
            int    read = 0;

            if (streamRead.CanRead)
            {
                read = streamRead.EndRead(result);
            }
            if (read > 0)
            {
                text += encoding.GetString(buffer, 0, read);
                streamRead.BeginRead(buffer, 0, buffer_size, ASyncReadResult, streamRead);
            }
            OnRaiseTextChanged(text);
        }
예제 #25
0
            private void ReceiveCallback(IAsyncResult ar)
            {
                try
                {
                    int byteLen = stream.EndRead(ar);
                    if (byteLen <= 0)
                    {
                        return;
                    }

                    byte[] data = new byte[byteLen];
                    Array.Copy(receiveBuffer, data, byteLen);

                    receivedData.Reset(HandleData(data));

                    // Restart reading
                    stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error reveiving TCP data:{e}");
                }
            }
예제 #26
0
        private void RecieveCallback(IAsyncResult _result)
        {
            try
            {
                int _byteLength = stream.EndRead(_result);
                if (_byteLength <= 0)
                {
                    //TODO: disconnect
                    return;
                }

                byte[] _data = new byte[_byteLength];
                Array.Copy(recieveBuffer, _data, _byteLength);

                //TODO: handle data
                recievedData.Reset(HandleData(_data));
                stream.BeginRead(recieveBuffer, 0, dataBufferSize, RecieveCallback, null);
            }
            catch
            {
                //TODO: Disconnect
            }
        }
예제 #27
0
        private void ReceiveCallback(IAsyncResult result)
        {
            try
            {
                int byteLength = _stream.EndRead(result);
                if (byteLength <= 0)
                {
                    _instance.Disconnect();
                    return;
                }

                byte[] data = new byte[byteLength];
                Array.Copy(_receiveBuffer, data, byteLength);

                _receivedData.Reset(HandleData(data));

                _stream.BeginRead(_receiveBuffer, 0, _dataBufferSize, ReceiveCallback, null);
            }
            catch
            {
                Disconnect();
            }
        }
예제 #28
0
            private void ReceiveCallback(IAsyncResult result)
            {
                try
                {
                    int byteLength = _stream.EndRead(result);
                    if (byteLength <= 0)
                    {
                        Server.Clients[_id].Disconnect();
                        return;
                    }

                    byte[] data = new byte[byteLength];
                    Array.Copy(_receiveBuffer, data, byteLength);

                    _receivedData.Reset(HandleData(data));
                    _stream.BeginRead(_receiveBuffer, 0, DataBufferSize, ReceiveCallback, null);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Server.Clients[_id].Disconnect();
                }
            }
예제 #29
0
            private void ReceiveCallback(IAsyncResult _result)
            {
                try
                {
                    int _byteLength = stream.EndRead(_result);
                    if (_byteLength <= 0)
                    {
                        // TODO : disconnect
                        return;
                    }

                    byte[] _data = new byte[_byteLength];
                    Array.Copy(receiveBuffer, _data, _byteLength);

                    receivedData.Reset(HandleData(_data));
                    stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
                }
                catch (Exception _ex)
                {
                    Console.WriteLine($"Error receiving TCP data: {_ex}");
                    // TODO: Disconnect
                }
            }
        /// <summary>
        /// Callback-Methode die nach dem Verbinden zum Server aufgerufen wird.
        /// </summary>
        /// <param name="result"></param>
        private void ConnectCallback(IAsyncResult result)
        {
            try
            {
                // Beendet den Verbindungsversuch und schreibt benötigte Rückgabewerte in result.
                this.TcpClient.EndConnect(result);

                // Führt das Event Connected aus.

                // Holt den Stream und beginnt einen asynchronen Lesezyklus (neuer Thread).
                NetworkStream networkStream = TcpClient.GetStream();
                networkStream.BeginRead(this.buffer, 0, buffer.Length, readCallback, null);
            }
            catch (SocketException)
            {
                OnConnectionFailed(EventArgs.Empty);
            }
            catch (Exception ex)
            {
                throw new Exception("Fehler beim Verbinden zum Server.", ex);
            }
            OnConnected(new ClientConnectedEventArgs(TcpClient));
        }
예제 #31
0
            private void ReceiveCallback(IAsyncResult result)
            {
                try
                {
                    int byteLength = stream.EndRead(result);
                    if (byteLength <= 0)
                    {
                        Server.clients[id].Disconnect();
                        return;
                    }

                    byte[] _data = new byte[byteLength];
                    Array.Copy(receiveBuffer, _data, byteLength);

                    receivedData.Reset(HandleData(_data));
                    stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error receiving TCP data: {ex}");
                    Server.clients[id].Disconnect();
                }
            }
예제 #32
0
        /// <summary>
        /// Creates a new instance of a <see cref="TCPClient"/>.
        /// </summary>
        /// <param name="id">The identifier number of connected client.</param>
        /// <param name="socketClient">The tcp client from connected client.</param>
        /// <param name="messageReceivedHandler">The callback of message received handler implementation.</param>
        /// <param name="clientDisconnectedHandler">The callback of client disconnected handler implementation.</param>
        /// <param name="maxMessageBuffer">The max length of message buffer.</param>
        public TCPClient(ushort id, Socket socketClient, MessageReceivedHandler messageReceivedHandler, ClientDisconnectedHandler clientDisconnectedHandler, ushort maxMessageBuffer)
        {
            try
            {
                _socketClient              = socketClient;
                _messageReceivedHandler    = messageReceivedHandler;
                _clientDisconnectedHandler = clientDisconnectedHandler;

                _socketClient.ReceiveBufferSize = maxMessageBuffer;
                _socketClient.SendBufferSize    = maxMessageBuffer;
                _buffer = new byte[maxMessageBuffer];
                _stream = new NetworkStream(_socketClient);

                Id        = id;
                IpAddress = _socketClient.RemoteEndPoint.ToString();

                _stream.BeginRead(_buffer, 0, _socketClient.ReceiveBufferSize, ReceiveDataCallback, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}.");
            }
        }
예제 #33
0
        /// <summary>Reads incoming data from the stream.</summary>
        private void ReceiveCallback(IAsyncResult _result)
        {
            try
            {
                int _byteLength = stream.EndRead(_result);
                if (_byteLength <= 0)
                {
                    Server.clients[id].Disconnect();
                    return;
                }

                byte[] _data = new byte[_byteLength];
                Array.Copy(receiveBuffer, _data, _byteLength);

                receivedData.Reset(HandleData(_data)); // Reset receivedData if all data was handled
                stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
            }
            catch (Exception _ex)
            {
                Debug.Log($"Error receiving TCP data: {_ex}");
                Server.clients[id].Disconnect();
            }
        }
예제 #34
0
        private void ReceiveCallback(IAsyncResult result)
        {
            try
            {
                int byteLenght = _stream.EndRead(result);
                if (byteLenght <= 0)
                {
                    Instance.Disconnect();
                    return;
                }

                byte[] data = new byte[byteLenght];
                Array.Copy(_receiveBuffer, data, byteLenght);

                _receivedData.Reset(HandleData(data));
                _stream.BeginRead(_receiveBuffer, 0, DataBufferSize, ReceiveCallback, null);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine($"Error receiving TCP data: {ex}");
                Disconnect();
            }
        }
        private void ReceiveCallback(IAsyncResult AR)
        {
            try
            {
                // Size of bytes received
                int byteLength = stream.EndRead(AR);
                if (byteLength <= 0)
                {
                    Client client = GameObject.FindObjectOfType <Client>();
                    client.Disconnect();
                    return;
                }
                else
                {
                    // Create a new EMPTY byte array to copy the new data into
                    byte[] data = new byte[byteLength];

                    // NOTE:(Nathen) Out data in currently in the "receive Buffer" client member
                    // We need to copy  it into the byte array we just created
                    Array.Copy(receiveBuffer, data, byteLength);

                    // NOTE:(Nathen) TCP does not always return ALL the data, sometimes we can receive,
                    // only some of the data. So we need to make sure that we have All of your data be from
                    // doing something with it

                    // Do something with that data
                    receivedData.Reset(HandleData(data));

                    // Keep reading
                    stream.BeginRead(receiveBuffer, 0, DataBufferSize, ReceiveCallback, null);
                }
            }
            catch (Exception e)
            {
                Disconnect();
            }
        }
        /// <summary>
        /// Callback-Methode für das Akzeptieren von Clienten.
        /// Wird aufgerufen wenn ein Client sich verbindet.
        /// </summary>
        /// <param name="result"></param>
        private void acceptTcpClientCallback(IAsyncResult result)
        {
            //try
            //{
                // Prüfen ob der Server korrekt läuft und nicht beendet wurde (Microsoft-Fehler).
                if (tcpListener.Server != null && tcpListener.Server.IsBound)
                {
                    // Verbindungsversuch vom Clienten abschließen
                    TcpClient tcpClient = tcpListener.EndAcceptTcpClient(result);

                    // Puffergrößte für den Clienten setzen.
                    byte[] buffer = new byte[tcpClient.ReceiveBufferSize];
                    Client client = new Client(tcpClient, buffer);

                    // clients sperren und Clienten hinzufügen.
                    lock (this.clients)
                    {
                        this.clients.Add(client);
                    }

                    // Stream von Clienten holen und Lesevorgang für den Clienten starten.
                    // "readCallback" wird mit dem client in "result" aufgerufen.
                    NetworkStream networkStream = client.Networkstream;
                    networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, readCallback, client);


                    // Akzeptieren neuer Clienten starten.
                    tcpListener.BeginAcceptTcpClient(acceptTcpClientCallback, null);
                    // ClientConnected Event ausführen.
                    OnClientConnected(new ClientConnectedEventArgs(tcpClient));
                }
            //}
            //catch (Exception ex)
            //{
			//	throw new Exception("Fehler beim Verbindungsversuch eines Clienten.", ex);
            //}
        }
예제 #37
0
    public void Reconnect()
    {
        Debug.Log("Attempting re-establish connection to server.");

        client = new TcpClient();

        client.SendBufferSize    = 4096;
        client.ReceiveBufferSize = 4096;

        asyncBuffer = new byte[8192];

        IPAddress[]  remoteHost = Dns.GetHostAddresses(ServerDomain);
        IAsyncResult result     = client.BeginConnect(remoteHost, port, null, null);

        try
        {
            client.EndConnect(result);
        }
        catch (Exception)
        {
            isConnected = false;
        }

        if (!client.Connected)
        {
            Invoke("Reconnect", 5.0f);
        }
        else
        {
            stream = client.GetStream();
            stream.BeginRead(asyncBuffer, 0, asyncBuffer.Length, OnReceivedData, null);

            isConnected = true;

            Debug.Log("Successfully connected to the server.");
        }
    }
        public override void OnTest(string[] args)
        {
            if (args.Length < 2 || args.Length > 3)     // 파라미터 개수 확인
            {
                throw new ArgumentException("Parameters: <Server> <Word> [<Port>]");
            }
            String server = args[0];        // 서버명 혹은 IP 주소

            // 포트 번호가 파라미터로 입력되었는지를 확인. 아닐 경우 7로 사용한다.
            int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;

            Console.WriteLine("Thread {0} ({1}) - Main()",
                              Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.ThreadState);
            // 해당 서버 포트에 접속하는 TcpClient 객체를 생성한다.
            TcpClient client = new TcpClient();

            client.Connect(server, servPort);
            Console.WriteLine("Thread {0} ({1}) - Main(): connected to server",
                              Thread.CurrentThread.GetHashCode(), Thread.CurrentThread.ThreadState);

            NetworkStream netStream = client.GetStream();
            ClientState   cs        = new ClientState(netStream, Encoding.ASCII.GetBytes(args[1]));
            // 인코딩 된 스트링을 서버로 전송한다.
            IAsyncResult result = netStream.BeginWrite(cs.ByteBuffer, 0,
                                                       cs.ByteBuffer.Length, new AsyncCallback(WriteCallback), cs);

            doOtherStuff();
            result.AsyncWaitHandle.WaitOne();       // EndWrite() 메소드 호출때까지 블록
            // 서버로부터 동일한 스트링을 다시 수신한다.
            result = netStream.BeginRead(cs.ByteBuffer, cs.TotalBytes,
                                         cs.ByteBuffer.Length - cs.TotalBytes, new AsyncCallback(ReadCallback), cs);
            doOtherStuff();
            ReadDone.WaitOne(); // ReadDone 이 수동적으로 설정될 때까지 블록을 건다.

            netStream.Close();  // 스트림을 종료한다.
            client.Close();     // 소켓 종료
        }
예제 #39
0
        /// <summary>
        /// 异步数据读取
        /// </summary>
        /// <param name="ar"></param>
        private void TCPReadCallBack(IAsyncResult ar)
        {
            StateObject st = (StateObject)ar.AsyncState;

            if (st.client == null || !st.client.Connected)
            {
                return;
            }

            int           nBytes;
            NetworkStream ns = st.client.GetStream();

            nBytes = ns.EndRead(ar);

            st.totalBytesRead += nBytes;
            if (nBytes > 0)
            {
                // 通过事件的方式通知数据
                if (StreamBuffer != null)
                {
                    byte[] data = new byte[nBytes];
                    Array.Copy(st.buffer, 0, data, 0, nBytes);
                    StreamBuffer(this, new StreamEventArgs(data));
                }

                // 监听数据
                ns.BeginRead(st.buffer, 0, StateObject.BufferSize,
                             new AsyncCallback(TCPReadCallBack), st);
            }
            else
            {
                ns.Close();
                st.client.Close();
                ns = null;
                st = null;
            }
        }
예제 #40
0
 private void SendMessage()
 {
     using (var client = new TcpClient(WorkflowSendSocketActionConfig.IPAddress, _port))
     {
         try
         {
             var dat = Encoding.ASCII.GetBytes("Hello World");
             using (var stream = client.GetStream())
             {
                 stream.BeginWrite(dat, 0, dat.Length, (res) =>
                 {
                     Debug.WriteLine("Finished writing");
                     var outBuffer         = new byte[2048];
                     NetworkStream rstream = (NetworkStream)res.AsyncState;
                     rstream.EndWrite(res);
                     rstream.BeginRead(outBuffer, 0, 2048,
                                       (ires) =>
                     {
                         var irstream = (NetworkStream)ires.AsyncState;
                         var count    = irstream.EndRead(ires);
                         Debug.WriteLine($"REad {count} bytes");
                         Debug.WriteLine($"Read through the buffer: {Encoding.ASCII.GetString(outBuffer, 0, count)}");
                         receiveDone.Set();
                     },
                                       rstream);
                     receiveDone.WaitOne();
                     sendDone.Set();
                 }, stream);
                 sendDone.WaitOne();
             }
         }
         catch (Exception e)
         {
             Debug.WriteLine(e.Message);
         }
     }
 }
예제 #41
0
    //Coroutine that manage client communication while client is connected to the server
    private IEnumerator ClientCommunication()
    {
        //Restart values in case there are more than one client connections
        m_bytesReceived = 0;
        m_buffer        = new byte[49152];

        //Stablish Client NetworkStream information
        m_netStream = m_client.GetStream();
        //While there is a connection with the client, await for messages
        do
        {
            ServerLog("Server is listening client msg...", Color.yellow);
            //Start Async Reading
            m_netStream.BeginRead(m_buffer, 0, m_buffer.Length, MessageReceived, m_netStream);

            //If there is any msg
            if (m_bytesReceived > 0)
            {
                ServerLog("Msg recived on Server: " + "<b>" + m_receivedMessage + "</b>", Color.green);
                //If message received from client is "Close", send another "Close" to the client
                if (m_receivedMessage == "Close")
                {
                    //Build message to client
                    string sendMsg = responseMessage;                  //In this case we send "Close" to end the client connection
                    byte[] msgOut  = Encoding.ASCII.GetBytes(sendMsg); //Encode message as bytes
                    //Start Sync Writing
                    m_netStream.Write(msgOut, 0, msgOut.Length);
                    ServerLog("Msg sended to Client: " + "<b>" + sendMsg + "</b>", Color.blue);
                    //Close connection with the client
                    CloseConnection();
                }
            }
            yield return(new WaitForSeconds(waitingMessagesFrequency));
        } while (m_bytesReceived >= 0 && m_netStream != null);
        //The communication is over
        CloseConnection();
    }
예제 #42
0
        /// <summary>
        /// Starts listening for incoming data on this TCP connection
        /// </summary>
        protected override void StartIncomingDataListen()
        {
            if (!NetworkComms.ConnectionExists(ConnectionInfo.RemoteEndPoint, ConnectionType.TCP))
            {
                CloseConnection(true, 18);
                throw new ConnectionSetupException("A connection reference by endPoint should exist before starting an incoming data listener.");
            }

#if WINDOWS_PHONE
            var stream = socket.InputStream.AsStreamForRead();
            stream.BeginRead(dataBuffer, 0, dataBuffer.Length, new AsyncCallback(IncomingTCPPacketHandler), stream);
#else
            lock (delegateLocker)
            {
                if (NetworkComms.ConnectionListenModeUseSync)
                {
                    if (incomingDataListenThread == null)
                    {
                        incomingDataListenThread = new Thread(IncomingTCPDataSyncWorker);
                        //Incoming data always gets handled in a time critical fashion
                        incomingDataListenThread.Priority = NetworkComms.timeCriticalThreadPriority;
                        incomingDataListenThread.Name     = "IncomingDataListener";
                        incomingDataListenThread.Start();
                    }
                }
                else
                {
                    tcpClientNetworkStream.BeginRead(dataBuffer, 0, dataBuffer.Length, new AsyncCallback(IncomingTCPPacketHandler), tcpClientNetworkStream);
                }
            }
#endif

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Trace("Listening for incoming data from " + ConnectionInfo);
            }
        }
예제 #43
0
        /// <summary>
        /// Open connection to server "host", with port number "port"
        /// </summary>
        /// <returns>true if connection succeded, false otherwise</returns>
        /// <param name="host">Hostname to connect to</param>
        /// <param name="port">Port number for connection</param>
        public static bool Open(string host, int port)
        {
            bool status = true;

            try
            {
                client = new TcpClient(host, port);

                stream = client.GetStream();

                // Start reading tcp stream and call "ReadCallback" method when newLength data
                // will be received
                // initially, "newLength" is equal to 1, so first call to ReadCallback
                // will be done after reception of 1 byte.

                // received data are stored in buffer
                // Next reading will be done in ReadCallback method
                stream.BeginRead(buffer, 0, 1, new AsyncCallback(ReadCallback), message);
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: " + e);
                status = false;
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: " + e.ToString());
                status = false;
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown Exception: " + e.ToString());
                status = false;
            }

            return(status);
        }
예제 #44
0
        /// <summary>
        /// 数据接收委托函数
        /// </summary>
        /// <param name="result">传入参数</param>
        protected void DataRec(IAsyncResult result)
        {
            if (IsOnline())
            {
                int         length = networkstream.EndRead(result); //获取接收数据的长度
                List <byte> data   = new List <byte>();             //新建byte数组
                data.AddRange((byte[])result.AsyncState);           //获取数据
                data.RemoveRange(length, data.Count - length);      //根据长度移除无效的数据
                byte[] data2 = new byte[1000];                      //重新定义接收缓冲

                bool c = tcpclient.Connected;
                networkstream.BeginRead(data2, 0, 1000, new AsyncCallback(DataRec), data2);  //重新挂起数据的接收等待
                //自定义代码区域,处理数据data
                //for (int i = 0; i < data.Count;i++ )
                //{
                //    Debug.WriteLine(data[i]);
                //}
                Encoding receiveEncoding_ = Encoding.UTF8;
                string   receiveStr       = receiveEncoding_.GetString((byte[])result.AsyncState, 0, length);
                receivedMessage = receiveStr;
                receivedMessageCount++;
                //  Debug.WriteLine(receiveStr);

                TCPEventArgs e = new TCPEventArgs(receiveStr);
                OnReceived(e);

                if (length == 0)
                {
                    //连接已经关闭
                    Debug.WriteLine("connection closed by server----------------");
                }
            }
            else
            {
                ReConnect();
            }
        }
예제 #45
0
 public void Connect(string host, int port)
 {
     Host = host;
     Port = port;
     if ((Host != "") && (Port != 0))
     {
         // разрешаем DNS или парсим адрес в IPAddress
         IPAddress parseAddress;
         var       list = IPAddress.TryParse(Host, out parseAddress) ? new[] { parseAddress } : Dns.GetHostEntry(Host).AddressList;
         // по каждому адресу из списка разрешения пытаемся подключиться
         foreach (IPAddress address in list)
         {
             client = new TcpClient();
             client.ReceiveBufferSize = client.SendBufferSize = 65536;
             var connectionTask = client.ConnectAsync(address, Port);
             connectionTask.Wait(3000);
             if (connectionTask.IsCompleted)
             {
                 break;
             }
         }
         // если не удалось подключиться - вылетаем
         if (!client.Connected)
         {
             throw new Exception("Не удалось установить подключение к серверу");
         }
         clientStream = client.GetStream();
         OnConnected?.Invoke();
         // начало чтения из сетевого потока
         message = new byte[client.ReceiveBufferSize];
         clientStream.BeginRead(message, 0, message.Length, Listen, message);
     }
     else
     {
         throw new Exception("Адрес сервера или порт не установлены");
     }
 }
예제 #46
0
        /// <summary>
        /// Обратный метод завершения принятия клиентов
        /// </summary>
        public void AcceptCallback(IAsyncResult ar)
        {
            if (modeNetwork == Mode.indeterminately)
            {
                return;
            }

            TcpListener listener = (TcpListener)ar.AsyncState;

            try
            {
                _tcpClient           = new TcpClientData();
                _tcpClient.tcpClient = listener.EndAcceptTcpClient(ar);


                // Немедленно запускаем асинхронный метод извлечения сетевых данных
                // для акцептированного TCP клиента
                NetworkStream ns = _tcpClient.tcpClient.GetStream();
                _tcpClient.buffer = new byte[global.LENGTHHEADER];
                ns.BeginRead(_tcpClient.buffer, 0, _tcpClient.buffer.Length, new AsyncCallback(ReadCallback), _tcpClient);


                // Продолжаем ждать запросы на подключение
                listener.BeginAcceptTcpClient(AcceptCallback, listener);

                // Активация события успешного подключения клиента
                if (Accept != null)
                {
                    Accept.BeginInvoke(this, null, null);
                }
            }
            catch
            {
                // Обработка исключительных ошибок возникших при акцептирования клиента.
                SoundError();
            }
        }
예제 #47
0
    /// <summary>
    /// Callback for the read opertaion.
    /// </summary>
    /// <param name="result">The async result object</param>
    private void ReadCallback(IAsyncResult result)
    {
        Client client = result.AsyncState as Client;

        if (client == null)
        {
            return;
        }
        NetworkStream networkStream = client.NetworkStream;
        int           read          = networkStream.EndRead(result);

        if (read == 0)
        {
            lock (this.clients)
            {
                if (DisConnectClient != null)
                {
                    DisConnectClient();
                }
                this.clients.Remove(client);
                return;
            }
        }
        string data = this.Encoding.GetString(client.Buffer, 0, read);

        //Do something with the data object here.
        networkStream.BeginRead(client.Buffer, 0, client.Buffer.Length, ReadCallback, client);

        if (this.MessageBytesReceived != null)
        {
            this.MessageBytesReceived(client.Buffer); // dispatch
        }
        if (this.MessageReceived != null)
        {
            this.MessageReceived(data);             // dispatch
        }
    }
예제 #48
0
        void EndReadCallback(IAsyncResult ar)
        {
            //var stateea = (CtkNonStopTcpStateEventArgs)ar.AsyncState;
            var myea = (CtkNonStopTcpStateEventArgs)ar.AsyncState;

            try
            {
                var client = myea.WorkTcpClient;
                if (!ar.IsCompleted || client == null || client.Client == null || !client.Connected)
                {
                    throw new CtkException("Read Fail");
                }

                var           ctkBuffer = myea.TrxMessageBuffer;
                NetworkStream stream    = client.GetStream();
                int           bytesRead = stream.EndRead(ar);
                ctkBuffer.Length = bytesRead;
                //呼叫他人不應影響自己運作, catch起來
                try { this.OnDataReceive(myea); }
                catch (Exception ex) { CtkLog.Write(ex); }

                if (this.IsAsynAutoRead)
                {
                    stream.BeginRead(ctkBuffer.Buffer, 0, ctkBuffer.Buffer.Length, new AsyncCallback(EndReadCallback), myea);
                }
            }
            //catch (IOException ex) { CtkLog.Write(ex); }
            catch (Exception ex)
            {
                //讀取失敗, 中斷連線(會呼叫 OnDisconnect), 不需要呼叫 OnFailConnect
                this.Disconnect();
                myea.Message   = ex.Message;
                myea.Exception = ex;
                this.OnErrorReceive(myea);//但要呼叫 OnErrorReceive
                CtkLog.WarnNs(this, ex);
            }
        }
예제 #49
0
        /**
         *  @brief      TcpClientStart
         *  @param[in]  string  ipAddStr    ServerIPAddress
         *  @param[in]  int     portno      PortNo
         *  @param[in]  string  sndStr      送信文字列
         *  @return     void
         *  @note       TcpClient接続、コマンド送信、受信待ち開始
         */
        bool TcpClientStart(string ipAddStr, int portno, string sndStr)
        {
            try
            {
                readBytes = new byte[512];

                // TcpClinet でコマンド送信
                tcpClient = new System.Net.Sockets.TcpClient(ipAddStr, portno);
                ntstrm = tcpClient.GetStream();

                // コマンドを Byte型に変換
                sndStr = sndStr + "\r\n";
                byte[] sendBytes = Encoding.ASCII.GetBytes(sndStr);

                // コマンド送信
                ntstrm.Write(sendBytes, 0, sendBytes.Length);

                // Ack/Nack 受信待ち。 callback Method登録
                ntstrm.BeginRead(readBytes, 0, readBytes.Length, new AsyncCallback(RecvCallback), null);
                return true;
            }
            catch(System.Net.Sockets.SocketException skerr)
            {
                if (ntstrm != null)
                {
                    ntstrm.Close();
                    ntstrm = null;
                }
                if (tcpClient != null)
                {
                    tcpClient.Close();
                    tcpClient = null;
                }
                skerr.ToString();
                return false;
            }
        }
예제 #50
0
        /// <summary>
        /// Event for Server Connection
        /// </summary>
        /// <param name="ar"></param>
        private void OnConnectionReady(IAsyncResult ar)
        {
            reconnectTimer.Stop();
            attemptReconnect = true;

            if (serverSocket == null)
            {
                if (ServerError != null)
                    ServerError(this, "Null Socket - Can not Connect", false);
                return;
            }

            try
            {
                serverSocket.EndConnect(ar);
            }
            catch (SocketException se)
            {
                if (ServerError != null)
                    ServerError(this, "Socket Exception Error " + se.ErrorCode + ":" + se.Message, false);

                disconnectError = true;
                ForceDisconnect();
                return;
            }
            catch (Exception e)
            {
                if (ServerError != null)
                    ServerError(this, "Exception Error: " + e.Message, false);

                disconnectError = true;
                ForceDisconnect();
                return;
            }

            socketStream = new NetworkStream(serverSocket, true);

            if (serverSetting.UseSSL)
            {
                try
                {
                    sslStream = new SslStream(socketStream, true, this.RemoteCertificateValidationCallback);
                    sslStream.AuthenticateAsClient(serverSetting.ServerName);
                    ServerMessage(this, "*** You are connected to this server with " + sslStream.SslProtocol.ToString().ToUpper() + "-" + sslStream.CipherAlgorithm.ToString().ToUpper() + sslStream.CipherStrength + "-" + sslStream.HashAlgorithm.ToString().ToUpper() + "-" + sslStream.HashStrength + "bits");
                }
                catch (System.Security.Authentication.AuthenticationException ae)
                {
                    if (ServerError != null)
                        ServerError(this, "SSL Authentication Error :" + ae.Message.ToString(), false);
                }
                catch (Exception e)
                {
                    if (ServerError != null)
                        ServerError(this, "SSL Exception Error :" + e.Message.ToString(), false);
                }
            }

            try
            {
                if (serverSetting.UseSSL)
                {
                    if (sslStream != null && sslStream.CanRead)
                    {
                        readBuffer = new byte[BUFFER_SIZE];
                        sslStream.BeginRead(readBuffer, 0, readBuffer.Length, new AsyncCallback(OnReceivedData), socketStream);
                    }
                }
                else
                {
                    if (socketStream != null && socketStream.CanRead)
                    {
                        readBuffer = new byte[BUFFER_SIZE];
                        socketStream.BeginRead(readBuffer, 0, readBuffer.Length, new AsyncCallback(OnReceivedData), socketStream);
                    }
                }

                this.serverSetting.ConnectedTime = DateTime.Now;

                RefreshServerTree(this);

                if (serverSetting.UseProxy)
                {

                    //socks v5 code
                    byte[] d = new byte[256];
                    ushort nIndex = 0;
                    d[nIndex++] = 0x05;

                    if (serverSetting.ProxyUser.Length > 0)
                    {
                        d[nIndex++] = 0x02;
                        d[nIndex++] = 0x00;
                        d[nIndex++] = 0x02;
                    }
                    else
                    {
                        d[nIndex++] = 0x01;
                        d[nIndex++] = 0x00;
                    }

                    try
                    {
                        socketStream.BeginWrite(d, 0, nIndex, new AsyncCallback(OnSendData), socketStream);

                        if (ServerMessage != null)
                            ServerMessage(this, "Socks 5 Connection Established with " + serverSetting.ProxyIP);
                    }
                    catch (SocketException)
                    {
                        System.Diagnostics.Debug.WriteLine("Error Sending Proxy Data");
                    }
                    catch (Exception)
                    {
                        System.Diagnostics.Debug.WriteLine("proxy exception");
                    }
                }
                else
                {
                    ServerPreConnect(this);

                    if (serverSetting.Password != null && serverSetting.Password.Length > 0)
                        SendData("PASS " + serverSetting.Password);

                    if (serverSetting.UseBNC == true && serverSetting.BNCPass != null && serverSetting.BNCPass.Length > 0)
                        SendData("PASS " + serverSetting.BNCPass);

                    //send the USER / NICK stuff
                    SendData("NICK " + serverSetting.NickName);

                    if (serverSetting.UseBNC == true && serverSetting.BNCUser != null && serverSetting.BNCUser.Length > 0)
                        SendData("USER " + serverSetting.BNCUser + " \"localhost\" \"" + serverSetting.BNCIP + "\" :" + serverSetting.FullName);
                    else
                        SendData("USER " + serverSetting.IdentName + " \"localhost\" \"" + serverSetting.ServerName + "\" :" + serverSetting.FullName);

                    whichAddressinList = whichAddressCurrent;

                    if (serverSetting.UseBNC == true)
                        this.fullyConnected = true;

                    this.pongTimer.Start();
                }
            }

            catch (SocketException se)
            {
                System.Diagnostics.Debug.WriteLine("CODE:" + se.SocketErrorCode);
                System.Diagnostics.Debug.WriteLine("ST:"+ se.StackTrace);

                if (ServerError != null)
                    ServerError(this, "Socket Exception Error:" + se.Message.ToString() + ":" + se.ErrorCode, false);

                disconnectError = true;
                ForceDisconnect();
            }
            catch (Exception e)
            {
                if (ServerError != null)
                    ServerError(this, "Exception Error:" + serverSetting.UseBNC + ":" + e.Message.ToString(), false);

                disconnectError = true;
                ForceDisconnect();
            }
        }
예제 #51
0
 private int Read(NetworkStream stream, byte[] buffer, int count)
 {
     var ar = stream.BeginRead(buffer, 0, count, null, null);
     if (!ar.AsyncWaitHandle.WaitOne(SocksTimeout))
     {
         throw new SocksException("The proxy did not respond in a timely manner.");
     }
     count = stream.EndRead(ar);
     if (count < 2)
     {
         throw new SocksException("Unable to negotiate with the proxy.");
     }
     return count;
 }
예제 #52
0
파일: Proxy.cs 프로젝트: FaNtA91/pokemonapi
        private void ParseFirstClientMsg()
        {
            try
            {
                clientRecvMsg.Position = clientRecvMsg.GetPacketHeaderSize();

                OutgoingPacketType protocolId = (OutgoingPacketType)clientRecvMsg.GetByte();
                int position;

                switch (protocolId)
                {
                    case OutgoingPacketType.LoginServerRequest:

                        protocol = Protocol.Login;
                        clientRecvMsg.GetUInt16();
                        ushort clientVersion = clientRecvMsg.GetUInt16();

                        clientRecvMsg.GetUInt32();
                        clientRecvMsg.GetUInt32();
                        clientRecvMsg.GetUInt32();

                        position = clientRecvMsg.Position;

                        clientRecvMsg.RsaOTDecrypt();

                        if (clientRecvMsg.GetByte() != 0)
                        {
                            Restart();
                            return;
                        }

                        xteaKey[0] = clientRecvMsg.GetUInt32();
                        xteaKey[1] = clientRecvMsg.GetUInt32();
                        xteaKey[2] = clientRecvMsg.GetUInt32();
                        xteaKey[3] = clientRecvMsg.GetUInt32();

                        clientRecvMsg.GetUInt32(); // account number
                        clientRecvMsg.GetString(); // password

                        clientRecvMsg.RsaOTEncrypt(position);

                        clientRecvMsg.InsertPacketHeader();

                        serverTcp = new TcpClient(loginServers[selectedLoginServer].Server, loginServers[selectedLoginServer].Port);
                        serverStream = serverTcp.GetStream();
                        serverStream.Write(clientRecvMsg.GetBuffer(), 0, clientRecvMsg.Length);
                        serverStream.BeginRead(serverRecvMsg.GetBuffer(), 0, 2, new AsyncCallback(ServerReadCallBack), null);
                        //clientStream.BeginRead(clientRecvMsg.GetBuffer(), 0, 2, new AsyncCallback(ClientReadCallBack), null);
                        break;

                    case OutgoingPacketType.GameServerRequest:

                        protocol = Protocol.World;

                        clientRecvMsg.GetUInt16();
                        clientRecvMsg.GetUInt16();

                        position = clientRecvMsg.Position;

                        clientRecvMsg.RsaOTDecrypt();

                        if (clientRecvMsg.GetByte() != 0)
                        {
                            Restart();
                            return;
                        }

                        xteaKey[0] = clientRecvMsg.GetUInt32();
                        xteaKey[1] = clientRecvMsg.GetUInt32();
                        xteaKey[2] = clientRecvMsg.GetUInt32();
                        xteaKey[3] = clientRecvMsg.GetUInt32();

                        clientRecvMsg.GetByte(); // GM mode

                        clientRecvMsg.GetUInt32(); // account number
                        string characterName = clientRecvMsg.GetString();

                        clientRecvMsg.GetString(); // password

                        clientRecvMsg.RsaOTEncrypt(position);

                        clientRecvMsg.InsertPacketHeader();

                        int index = GetSelectedIndex(characterName);

                        if (Version.CurrentVersion < 854)
                        {
                            serverTcp = new TcpClient(BitConverter.GetBytes(charList[index].WorldIP).ToIPString(), charList[index].WorldPort);
                            serverStream = serverTcp.GetStream();
                        }

                        serverStream.Write(clientRecvMsg.GetBuffer(), 0, clientRecvMsg.Length);
                        serverStream.BeginRead(serverRecvMsg.GetBuffer(), 0, 2, new AsyncCallback(ServerReadCallBack), null);
                        clientStream.BeginRead(clientRecvMsg.GetBuffer(), 0, 2, new AsyncCallback(ClientReadCallBack), null);

                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                WriteDebug(ex.ToString());
                Restart();
            }
        }
예제 #53
0
파일: Proxy.cs 프로젝트: FaNtA91/pokemonapi
        private void ListenClientCallBack(IAsyncResult ar)
        {
            try
            {
                if (!accepting)
                    return;

                accepting = false;

                clientSocket = loginClientTcp.EndAcceptSocket(ar);

                loginClientTcp.Stop();
                worldClientTcp.Stop();

                clientStream = new NetworkStream(clientSocket);
                clientStream.BeginRead(clientRecvMsg.GetBuffer(), 0, 2, new AsyncCallback(ClientReadCallBack), null);
            }
            catch (ObjectDisposedException) { /*We don't have to log this exception. */ }
            catch (Exception ex)
            {
                WriteDebug(ex.ToString());
                Restart();
            }
        }
예제 #54
0
 public User(TcpClient client, THEServer owner, int bufferSize = 1024)
 {
     this.client = client;
     this.owner = owner;
     this.bufferSize = bufferSize;
     networkStream = client.GetStream();
     //br = new BinaryReader(networkStream);
     //bw = new BinaryWriter(networkStream);
     buffer = new byte[bufferSize];
     state = State.Connected;
     Notice(GetNoticeEventArgs.GetClientLogin(owner, this));
     if (owner.isStopped == false)
     {
         //开始读取信息
         networkStream.BeginRead(buffer, 0, bufferSize, ReadCallback, new Object());
     }
 }
예제 #55
0
 /// <summary>
 /// 连接服务器
 /// </summary>
 /// <returns></returns>
 public bool Connect(IPEndPoint ipEndPoint = null)
 {
     if (state == State.Connecting) return false;
     if (ipEndPoint == null)
     {
         if (seversAddress == null)
         {
             return false;
         }
         else
         {
             ipEndPoint = this.ipEndPoint;
         }
     }
     tcpClient = new TcpClient();
     try
     {
         tcpClient.Connect(ipEndPoint);
     }
     catch
     {
         Notice(GetNoticeEventArgs.GetConnectFailed(this, ipEndPoint));
         return false;
     }
     networkStream = tcpClient.GetStream();
     state = State.Connecting;
     networkStream.BeginRead(buffer, 0, bufferSize, ReadCallback, new Object());
     Notice(GetNoticeEventArgs.GetConnectSucceed(this, ipEndPoint));
     return true;
 }
예제 #56
0
 private void Connect(IPAddress ip, int port)
 {
     m_client = null;
     m_stream = null;
     m_connectionIsLost = 0;
     m_client = new TcpClient();
     m_client.Connect(ip, port);
     m_stream = m_client.GetStream();
     m_IPEndPoint = m_client.Client.LocalEndPoint;
     m_thisIP = m_client.Client.RemoteEndPoint;
     m_stream.BeginRead(ReadData, 0, ReadData.Length, ReceiverCallback, null);
     Thread lookingForServerThread = new Thread(LookingForServer);
 }
예제 #57
0
 private void AcceptCallback(IAsyncResult result)
 {
     var listener = (Socket)result.AsyncState;
     try
     {
         var client = listener.EndAccept(result);
         var clientStream = new NetworkStream(client);
         ConnectedClient c;
         lock (_clients)
         {
             c = new ConnectedClient(clientStream, new byte[5000], new MemoryStream());
             _clients.Add(c);
         }
         clientStream.BeginRead(c.Buffer, 0, c.Buffer.Length, ReadCompleted, c);
         if (_feedbackProvider != null)
             _feedbackProvider.ClientConnected(_currentIp, _currentPort, ClientCount);
     }
     catch (Exception ex)
     {
         WriteError(ex);
     }
     finally
     {
         listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
     }
 }
예제 #58
0
        /// <summary>
        /// Open network connection
        /// </summary>
        /// <param name="device_name">Device name or IP address</param>
        /// <param name="port">TCP port</param>
        /// <returns>true if opened succefully, otherwise false</returns>
        public override bool Open(string device_name, int port)
        {
            try
            {
                //Estabilish connection, get network stream for reading and writing
                tcp_client = new TcpClient(device_name, port);
                ns = tcp_client.GetStream();

                if (ns == null) return false;

                trying_to_close = false;
            }
            catch 
            {
                return false;
            }

            ns.Flush();

            //Start asyn-read
            ns.BeginRead(state.data, 0, BUFFER_SIZE, new AsyncCallback(OnDataRead), state);

            return true;
        }
예제 #59
0
파일: Chat.cs 프로젝트: t13554yt/CarMeter
	private IEnumerator ReadMessage(){
		stream = GetNetworkStream ();
		// 非同期で待ち受けする
		stream.BeginRead (readbuf, 0, readbuf.Length, new AsyncCallback (ReadCallback), null);
		isStopReading = true;
		yield return null;
	}
예제 #60
0
        //Asyn-call back
        private void DoAcceptTCPClientCallBack(IAsyncResult ar)
        {
            try
            {
                TcpListener listener = (TcpListener)ar.AsyncState;     
                TcpClient client = listener.EndAcceptTcpClient(ar);
    
                ns = client.GetStream();
                delegateClientConnected clientConn = new delegateClientConnected(TriggerOnClientConnect);
                clientConn.BeginInvoke(null, null);

                ns.BeginRead(state.data, 0, BUFFER_SIZE, new AsyncCallback(OnDataRead), state);
            }
            catch
            {
            }
        }