コード例 #1
0
ファイル: TcpListener.cs プロジェクト: swishcloud/181107
        public async void ListenAsync(string ip, int port)
        {
            if (Listening)
            {
                throw new Exception("Listening");
            }
            Listening = true;

            server = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port);
            server.Start();
            ListeningStarted(this, server);
            Env.Print($"listening: {server.LocalEndpoint.ToString()}");
            try
            {
                while (true)
                {
                    Env.Print("waiting for a connection");
                    var client = await server.AcceptTcpClientAsync();

                    Env.Print("one incoming tcp connection");

                    var session = new TcpClientSession(client);
                    NewSession.Invoke(this, session);
                    TcpClientAccepted?.Invoke(this, session);
                    session.Receive();
                }
            }
            catch (Exception ex)
            {
                Env.Print(ex.Message);
            }
        }
コード例 #2
0
        public async void Connect()
        {
            try
            {
                Client = new System.Net.Sockets.TcpClient(new IPEndPoint(IPAddress.Parse(IpAddressHelper.GetHostIp()), new Random().Next(80, 6000)));
                Env.Print($"connecting to {this.Ip}:{this.Port}");
                await Client.ConnectAsync(IPAddress.Parse(this.Ip), this.Port);

                Env.Print($"connected to {Client.Client.RemoteEndPoint} from {Client.Client.LocalEndPoint}");
                Session = new TcpClientSession(Client);
                NewSession(this, Session);
                Session.Disconnected += Disconnected;

                Connected?.Invoke(this, Session);
                Session.Receive();
            }
            catch (Exception ex)
            {
                Env.Print($"connect failed.cause:{ex.Message}");
                ConnectFailed(this, ex);
            }
        }