Example #1
1
 public void Start(string[] args)
 {
     registry = new Registry();
     if (!registry.Register(this))
     {
         Console.WriteLine("Error registering service.");
         return;
     }
     Console.WriteLine("Registered service.");
     try
     {
         TcpClient tcpclient = new TcpClient();
         if (args.Count() != 2)
             throw new Exception("Argument must contain a publishing ip and port. call with: 127.0.0.1 12345");
         tcpclient.Connect(args[0], Int32.Parse(args[1]));
         StreamReader sr = new StreamReader(tcpclient.GetStream());
         string data;
         while ((data = sr.ReadLine()) != null)
         {
             Console.WriteLine("Raw data: " + data);
             if (RawAisData != null)
                 RawAisData(data);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message + e.StackTrace);
         Console.WriteLine("Press enter");
         Console.ReadLine();
     }
 }
Example #2
1
        /// <summary>
        /// 客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="message"></param>
        static void Client(string ip, int port, string message)
        {
            try
            {
                //1.发送数据
                TcpClient client = new TcpClient(ip, port);
                IPEndPoint ipendpoint = client.Client.RemoteEndPoint as IPEndPoint;
                NetworkStream stream = client.GetStream();
                byte[] messages = Encoding.Default.GetBytes(message);
                stream.Write(messages, 0, messages.Length);
                Console.WriteLine("{0:HH:mm:ss}->发送数据(to {1}):{2}", DateTime.Now, ip, message);

                //2.接收状态,长度<1024字节
                byte[] bytes = new Byte[1024];
                string data = string.Empty;
                int length = stream.Read(bytes, 0, bytes.Length);
                if (length > 0)
                {
                    data = Encoding.Default.GetString(bytes, 0, length);
                    Console.WriteLine("{0:HH:mm:ss}->接收数据(from {1}:{2}):{3}", DateTime.Now, ipendpoint.Address, ipendpoint.Port, data);
                }

                //3.关闭对象
                stream.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0:HH:mm:ss}->{1}", DateTime.Now, ex.Message);
            }
            Console.ReadKey();
        }
 public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter)
 {
     _client = client;
     _stream = stream;
     _binaryReader = binaryReader;
     _binaryWriter = binaryWriter;
 }
Example #4
1
 public ThreadClient(TcpClient cl, int i)
 {
     this.cl = cl;
     tuyen = new Thread(new ThreadStart(GuiNhanDL));
     tuyen.Start();
     this.i = i;
 }
        public Client(String host, Int32 port)
        {
            try
            {

                clientName = Dns.GetHostName();

            }
            catch (SocketException se)
            {

                MessageBox.Show("ERROR: Could not retrieve client's DNS hostname.  Please try again." + se.Message + ".", "Client Socket Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;

            }

            serverName = host;
            gamePort = port;
            client = new TcpClient(host, port);
            netStream = client.GetStream();
            reader = new StreamReader(netStream);
            writer = new StreamWriter(netStream);
            ssl = new SslStream(netStream, false, new RemoteCertificateValidationCallback(ValidateCert));
            cert = new X509Certificate2("server.crt");
            ssl.AuthenticateAsClient(serverName);
            writer.AutoFlush = true;
        }
 public void Connect(IPEndPoint remoteAddress)
 {
     BaseSocket = new TcpClient();
     BaseSocket.Connect(remoteAddress);
     OutputStream = new StreamWriter(new BufferedStream(BaseSocket.GetStream()));
     InputStream = new StreamReader(new BufferedStream(BaseSocket.GetStream()));
 }
Example #7
0
        private void bnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient(txtConnect.Text, 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);
                dato = sr.ReadLine()
                    + System.Environment.NewLine
                    + sr.ReadLine()
                    + System.Environment.NewLine
                    + sr.ReadLine();

                DelegadoRespuesta dr = new DelegadoRespuesta(EscribirFormulario);
                Invoke(dr);

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                throw;
            }


        }
Example #8
0
        private void handleClient(TcpClient socket)
        {
            string data;
            NetworkStream ns = socket.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);


            sw.WriteLine("Benvido, intenta adivinar o meu número");
            sw.Flush();


            try
            {
                while (true)
                {
                }
            }
            catch (Exception)
            {

                throw;
            }



        }
Example #9
0
 //private volatile bool gameStarted = false;
 public Jeu()
 {
     State = GameState.WaitingStartGame;
     serveur = new TcpClient("P104-14", 8080);
     Attente = new Thread(AttendreDebutPartie);
     Attente.Start();
 }
Example #10
0
        public void Connect(String server, String message)
        {
            try
            {


                Int32 port = 13000;
                client = new TcpClient(server, port);
                while (true)
                {
                    Recieve();
                    //Send();
                   

                }
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("ArgumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }

            Console.WriteLine("\n Press Enter to continue...");
            Console.Read();
        }
Example #11
0
        private void handleClient(TcpClient socket)
        {
            String rawData;
            String data;
            NetworkStream ns = socket.GetStream();
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);

            sw.WriteLine("@[email protected]@");
            sw.Flush();

            while (true)
            {
                try
                {
                    // do things
                    rawData = sr.ReadLine();

                    Console.WriteLine("Raw data: " + rawData); // debug
                    data = hexaToString(rawData);
                    Console.WriteLine("String data: " + data); // debug
                }
                catch (Exception err)
                {
                    //Console.WriteLine(err.ToString());
                    break;
                }

            }

            ns.Close();
            socket.Close();
            //  finish

        }
    internal TcpListenerWebSocketContext (
      TcpClient tcpClient,
      string protocol,
      bool secure,
      ServerSslConfiguration sslConfig,
      Logger logger)
    {
      _tcpClient = tcpClient;
      _secure = secure;
      _logger = logger;

      var netStream = tcpClient.GetStream ();
      if (secure) {
        var sslStream = new SslStream (
          netStream, false, sslConfig.ClientCertificateValidationCallback);

        sslStream.AuthenticateAsServer (
          sslConfig.ServerCertificate,
          sslConfig.ClientCertificateRequired,
          sslConfig.EnabledSslProtocols,
          sslConfig.CheckCertificateRevocation);

        _stream = sslStream;
      }
      else {
        _stream = netStream;
      }

      _request = HttpRequest.Read (_stream, 90000);
      _uri = HttpUtility.CreateRequestUrl (
        _request.RequestUri, _request.Headers["Host"], _request.IsWebSocketRequest, secure);

      _websocket = new WebSocket (this, protocol);
    }
Example #13
0
        public TcpTextWriter(string hostName, int port)
        {
            if (hostName == null)
                throw new ArgumentNullException(nameof(hostName));
            if ((port < 0) || (port > ushort.MaxValue))
                throw new ArgumentException("port");

            HostName = hostName;
            Port = port;

#if __IOS__ || MAC
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
#endif
            try
            {
#if __IOS__ || MAC || ANDROID
                var client = new TcpClient(hostName, port);
                writer = new StreamWriter(client.GetStream());
#elif WINDOWS_PHONE || NETFX_CORE
               
                var socket = new StreamSocket();
                socket.ConnectAsync(new HostName(hostName), port.ToString(CultureInfo.InvariantCulture))
                    .AsTask()
                    .ContinueWith( _ => writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()));
#endif
            }
            catch
            {
#if __IOS__ || MAC
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
#endif
                throw;
            }
        }
Example #14
0
        private Thread ziThread; //处理客户端请求的线程

        #endregion Fields

        #region Constructors

        public Agent(TcpClient client, NetworkStream streamToClient, string DataSourceIpOrPortA, string DataSourceIpOrPortB)
        {
            this.client = client;
            this.streamToClient = streamToClient;
            this.DataSourceIpOrPortA = DataSourceIpOrPortA;
            this.DataSourceIpOrPortB = DataSourceIpOrPortB;
        }
Example #15
0
 public TcpSocket(TcpClient tcpClient)
 {
     this._connection = tcpClient;
     this._connection.NoDelay = true;
     IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
     this._remoteAddress = (RemoteAddress)new TcpAddress(ipEndPoint.Address, ipEndPoint.Port);
 }
Example #16
0
 public User(TcpClient client)
 {
     this.client = client;
     NetworkStream networkStream = client.GetStream();
     br = new BinaryReader(networkStream);
     bw = new BinaryWriter(networkStream);
 }
Example #17
0
        public void TestListen()
        {
            try
            {
                Identd.Start("username");
                Thread.Sleep( 1000 );

                TcpClient client = new TcpClient();
                client.Connect("localhost", 113);

                StreamWriter writer = new StreamWriter( client.GetStream() );
                writer.WriteLine( "a query" );
                writer.Flush();

                StreamReader reader = new StreamReader( client.GetStream() );
                string line = reader.ReadLine();

                Identd.Stop();

                Assertion.AssertEquals( "a query : USERID : UNIX : username", line.Trim() );
            }
            catch( Exception e )
            {
                Assertion.Fail("IO Exception during test:" + e);
            }
        }
        public TestResultBase Test(Options o)
        {
            var p = new Uri(o.Url);

            var res = new GenericTestResult
            {
                ShortDescription = "TCP connection port " + p.Port,
                Status = TestResult.OK
            };

            try
            {
                var client = new TcpClient();
                client.Connect(p.DnsSafeHost, p.Port);
                res.Status = TestResult.OK;
                client.Close();
            }
            catch (Exception ex)
            {
                res.Status = TestResult.FAIL;
                res.CauseOfFailure = ex.Message;
            }

            return res;
        }
Example #19
0
        static void RunClient(object state)
        {
            Customer cust = Customer.Invent();
            Console.WriteLine("CLIENT: Opening connection...");
            using (TcpClient client = new TcpClient())
            {
                client.Connect(new IPEndPoint(IPAddress.Loopback, PORT));
                using (NetworkStream stream = client.GetStream())
                {
                    Console.WriteLine("CLIENT: Got connection; sending data...");
                    Serializer.SerializeWithLengthPrefix(stream, cust, PrefixStyle.Base128);
                    
                    Console.WriteLine("CLIENT: Attempting to read data...");
                    Customer newCust = Serializer.DeserializeWithLengthPrefix<Customer>(stream, PrefixStyle.Base128);
                    Console.WriteLine("CLIENT: Got customer:");
                    newCust.ShowCustomer();

                    Console.WriteLine("CLIENT: Sending happy...");
                    stream.WriteByte(123); // just to show all bidirectional comms are OK
                    Console.WriteLine("CLIENT: Closing...");
                    stream.Close();
                }
                client.Close();
            }
        }
Example #20
0
 private TcpClient ConnectRemote(IPEndPoint ipEndPoint)
 {
     TcpClient client = new TcpClient();
     try
     {
         client.Connect(ipEndPoint);
     }
     catch (SocketException socketException)
     {
         if (socketException.SocketErrorCode == SocketError.ConnectionRefused)
         {
             throw new ProducerException("服务端拒绝连接",
                                           socketException.InnerException ?? socketException);
         }
         if (socketException.SocketErrorCode == SocketError.HostDown)
         {
             throw new ProducerException("订阅者服务端尚未启动",
                                           socketException.InnerException ?? socketException);
         }
         if (socketException.SocketErrorCode == SocketError.TimedOut)
         {
             throw new ProducerException("网络超时",
                                           socketException.InnerException ?? socketException);
         }
         throw new ProducerException("未知错误",
                                           socketException.InnerException ?? socketException);
     }
     catch (Exception e)
     {
         throw new ProducerException("未知错误", e.InnerException ?? e);
     }
     return client;
 }
Example #21
0
        private string GetResponse(string apiVerb)
        {
            TcpClient tcpClient = new TcpClient("127.0.0.1", port);
            NetworkStream tcpStream = tcpClient.GetStream();

            Byte[] request = Encoding.ASCII.GetBytes(apiVerb);
            tcpStream.Write(request, 0, request.Length);

            Byte[] responseBuffer = new Byte[4096];
            string response = string.Empty;
            do
            {
                int bytesRead = tcpStream.Read(responseBuffer, 0, responseBuffer.Length);
                response = response + Encoding.ASCII.GetString(responseBuffer, 0, bytesRead);
            } while (tcpStream.DataAvailable);

            if (LogEvent != null)
            {
                LogEventArgs args = new LogEventArgs();

                args.DateTime = DateTime.Now;
                args.Request = apiVerb;
                args.Response = response;

                LogEvent(this, args);
            }

            tcpClient.Close();

            return response;
        }
Example #22
0
        private void AcceptClient(TcpClient client)
        {
            IRCClientView cv = new IRCClientView(client, m_baseScene);

            if (OnNewIRCClient != null)
                OnNewIRCClient(cv);
        }
        void LayDL()
        {
            try
            {
                cl = new Server_Client.Client();
                // gán TCPclient
                this.client1 = cl.Connect(Luu.IP, Luu.Ports);
                //truyền giá trị lên server
                clientstrem = cl.SerializeObj(this.client1, "LayBackUp", null);
                // đổ mảng đối tượng vào datagripview
                slht = (Entities.SaoLuuHeThong[])cl.DeserializeHepper1(clientstrem, null);
                if (slht != null)
                {
                    if (slht.Length > 0)
                    {
                        dgvHienThi.DataSource = slht;
                    }
                }
                else
                {
                    slht = new Entities.SaoLuuHeThong[0];
                    dgvHienThi.DataSource = slht;
                }
                fix();
            }
            catch
            {
                dgvHienThi.DataSource = new Entities.SaoLuuHeThong[0];
                fix();
            }

            dgvHienThi.Refresh();
        }
Example #24
0
        public DoctorThread(TcpClient client, Server server)
        {
            this.client = client;
            this.server = server;

            this.running = false;
        }
Example #25
0
 public static void Load(TcpClient client)
 {
     reader = new StreamReader(client.GetStream());
     Reader.client = client;
     
    
 }
Example #26
0
        private ProtoClient(ProtoClientConfiguration configuration, TcpClient tcpClient, string hostname)
        {
            Require.NotNull(hostname, "hostname");

            Configuration = configuration ?? new ProtoClientConfiguration();
            Configuration.Freeze();

            ServiceAssembly = ServiceRegistry.GetAssemblyRegistration(
                Configuration.ServiceAssembly ?? GetType().Assembly
            );

            var streamManager = Configuration.StreamManager ?? new MemoryStreamManager();

            _connection = new ClientConnection(this, tcpClient, hostname, streamManager);

            if (Configuration.CallbackObject != null)
            {
                Service service = null;

                if (!(Configuration.CallbackObject is IProtoMessageDispatcher))
                    service = ServiceAssembly.GetServiceRegistration(Configuration.CallbackObject.GetType());

                _connection.Client = new Client(configuration.CallbackObject, ServiceAssembly, service);
            }
        }
 public void testCon(string ip, int port)
 {
     TcpClient client = new TcpClient(ip,port);
     try{
         client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
         /*
         Stream s = client.GetStream();
         StreamReader sr = new StreamReader(s);
         StreamWriter sw = new StreamWriter(s);
         sw.AutoFlush = true;
         Console.WriteLine(sr.ReadLine());
         */
         while(true){
             //Console.Write("Name: ");
             //string name = Console.ReadLine();
             //sw.WriteLine(name);
             //if(name == "") break;
             //Console.WriteLine(sr.ReadLine());
         }
         //s.Close();
     }finally{
         // code in finally block is guranteed
         // to execute irrespective of
         // whether any exception occurs or does
         // not occur in the try block
         //client.Close();
     }
 }
Example #28
0
 public void Close()
 {
     if (client == null)
         return;
     client.SafeDispose();
     client = null;
 }
Example #29
0
        static void Main(string[] args)
        {
            var port = Convert.ToInt32(args[0]);
              var timeout = Convert.ToInt32(args[1]);
              var buffer = new byte[12];

              client = new TcpClient();
              client.Connect(IPAddress.Loopback, port);
              client.Client.BeginReceive(termBuffer, 0, 1, SocketFlags.None,
                                 inputClient_DataReceived, null);

              Console.WriteLine("Connected to Nexus at 127.0.0.1:{0}", port);

              Wiimotes.ButtonClicked += Button;
              int numConnnected = Wiimotes.Connect(timeout);

              if (numConnnected > 0) {
            Console.WriteLine("{0} wiimote(s) found", numConnnected);

            CopyInt(ref buffer, 1, 0);
            CopyInt(ref buffer, numConnnected, 4);
            CopyInt(ref buffer, 0, 8);

            client.Client.Send(buffer);
            Wiimotes.Poll();
              }
              else {
            CopyInt(ref buffer, 1, 0);
            CopyInt(ref buffer, 0, 4);
            CopyInt(ref buffer, 0, 8);

            client.Client.Send(buffer);
            Console.WriteLine("No Wiimotes found");
              }
        }
Example #30
0
        public void checkConflict()
        {
            Server_Client.Client client= new Server_Client.Client();
             this.tcpClient = client.Connect(Luu.IP, Luu.Ports);

             Entities.KhoHang kh = new Entities.KhoHang("Select");
             Entities.KhoHang[] kh1 = new Entities.KhoHang[1];
             networkStream = client.SerializeObj(this.tcpClient, "KhoHang", kh);

             kh1 = (Entities.KhoHang[])client.DeserializeHepper1(networkStream, kh1);
             if (kh1 != null)
             {
                 for (int j = 0; j < kh1.Length; j++)
                 {
                     if (kh1[j].MaKho == txtMaKho.Text)
                     {
                         MessageBox.Show("Thất bại");
                         chck = "No";
                         txtMaKho.Text = new Common.Utilities().ProcessID(txtMaKho.Text);
                         break;
                     }
                     else
                         chck = "Yes";
                 }
             }
        }