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 ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter)
 {
     _client = client;
     _stream = stream;
     _binaryReader = binaryReader;
     _binaryWriter = binaryWriter;
 }
예제 #3
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();
        }
예제 #4
1
 public ThreadClient(TcpClient cl, int i)
 {
     this.cl = cl;
     tuyen = new Thread(new ThreadStart(GuiNhanDL));
     tuyen.Start();
     this.i = i;
 }
예제 #5
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();
     }
 }
예제 #6
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("@CONNECTION@OK@");
            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

        }
예제 #7
0
        private void AcceptClient(TcpClient client)
        {
            IRCClientView cv = new IRCClientView(client, m_baseScene);

            if (OnNewIRCClient != null)
                OnNewIRCClient(cv);
        }
예제 #8
0
파일: Join.cs 프로젝트: kevinnieskes/Game
        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();
        }
예제 #9
0
 public void Close()
 {
     if (client == null)
         return;
     client.SafeDispose();
     client = null;
 }
        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;
        }
예제 #11
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);
            }
        }
예제 #12
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);
            }
        }
예제 #13
0
 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();
     }
 }
예제 #14
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";
                 }
             }
        }
예제 #15
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;
            }
        }
예제 #16
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;
        }
예제 #17
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();
            }
        }
예제 #18
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;
        }
예제 #19
0
 public User(TcpClient client)
 {
     this.client = client;
     NetworkStream networkStream = client.GetStream();
     br = new BinaryReader(networkStream);
     bw = new BinaryWriter(networkStream);
 }
예제 #20
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);
 }
예제 #21
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;
            }


        }
예제 #22
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;
            }



        }
예제 #23
0
 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()));
 }
예제 #24
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;
 }
    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);
    }
예제 #26
0
 //private volatile bool gameStarted = false;
 public Jeu()
 {
     State = GameState.WaitingStartGame;
     serveur = new TcpClient("P104-14", 8080);
     Attente = new Thread(AttendreDebutPartie);
     Attente.Start();
 }
예제 #27
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");
              }
        }
예제 #28
0
        public DoctorThread(TcpClient client, Server server)
        {
            this.client = client;
            this.server = server;

            this.running = false;
        }
예제 #29
0
 public static void Load(TcpClient client)
 {
     reader = new StreamReader(client.GetStream());
     Reader.client = client;
     
    
 }
        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();
        }
예제 #31
0
        void ProcessClient(System.Net.Sockets.TcpClient client)
        {
            Stream dataStream = null;

            try
            {
                // A client has connected. Create the
                // SslStream using the client's network stream.
                dataStream = ConnectClient(client);
                // Set timeouts for the read and write.
                dataStream.ReadTimeout  = TcpSettings.ReadTimeout;
                dataStream.WriteTimeout = TcpSettings.WriteTimeout;

                if (Connected != null)
                {
                    Connected(this, new ConnectedEventArgs(this, client, dataStream));
                }
            }
            catch (IOException) { }
            catch (ThreadAbortException) { throw; }
            catch (AuthenticationException e)
            {
                Log.Error(e);
                Log.Verbose("Authentication failed - closing the connection.");
            }
            finally
            {
                // The client stream will be closed with the dataStream
                // because we specified this behavior when creating
                // the dataStream.
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                client.Close();
            }
        }
예제 #32
0
        //受信開始ボタン
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                tcp         = new System.Net.Sockets.TcpClient(ipOrHost, port);
                tcp.NoDelay = true;

                label8.Text     = "Client:" + ipOrHost + " :" + port;
                ns              = tcp.GetStream();
                ns.ReadTimeout  = Timeout.Infinite;
                ns.WriteTimeout = Timeout.Infinite;
                enc             = System.Text.Encoding.UTF8;

                tcpflag = true;

                TcpReadThread = new Thread(TcpRead);
                TcpReadThread.IsBackground = true;
                TcpReadThread.Priority     = System.Threading.ThreadPriority.Normal;
                TcpReadThread.Start();

                MotionThread = new Thread(TcpFunc);
                MotionThread.IsBackground = true;
                MotionThread.Priority     = System.Threading.ThreadPriority.Normal;
                MotionThread.Start();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }

            textBox7.Enabled  = true;
            groupBox2.Enabled = true;

            //タイマーの作成
            boringTimer.Interval = 1000;
            boringTimer.Tick    += new EventHandler(timer_tick);
        }
예제 #33
0
        private async void InitListener()
        {
            var tcpServer = new Sockets.TcpListener(IPAddress.Any, ClientListenerPort);

            tcpServer.Start();

            while (true)
            {
                tcpReciever = await tcpServer.AcceptTcpClientAsync();

                var stream = tcpReciever.GetStream();
                properlyDisconnected = false;

                while (true)
                {
                    var message = TcpUtils.ReadMessage(stream);
                    if (string.IsNullOrEmpty(message))
                    {
                        if (!properlyDisconnected)
                        {
                            Invoke(new Action(() =>
                            {
                                MessageBox.Show(this,
                                                "Соединение с сервером потеряно. Подключение будет закрыто",
                                                "Сервер отключен",
                                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                                Disconnect();
                            }));
                        }
                        break;
                    }

                    message = DateTime.Now.ToString("t") + ": " + message;
                    lbMessages.Invoke(new Action(() => lbMessages.Items.Add(message)));
                }
            }
        }
예제 #34
0
        /// <summary>
        /// Dispose of the TCP client.
        /// </summary>
        public void Dispose()
        {
            _Connected = false;

            if (_TokenSource != null)
            {
                if (!_TokenSource.IsCancellationRequested)
                {
                    _TokenSource.Cancel();
                }
                _TokenSource.Dispose();
                _TokenSource = null;
            }

            if (_SslStream != null)
            {
                _SslStream.Close();
                _SslStream.Dispose();
                _SslStream = null;
            }

            if (_NetworkStream != null)
            {
                _NetworkStream.Close();
                _NetworkStream.Dispose();
                _NetworkStream = null;
            }

            if (_TcpClient != null)
            {
                _TcpClient.Close();
                _TcpClient.Dispose();
                _TcpClient = null;
            }

            Log("Dispose complete");
        }
예제 #35
0
        byte[] readBytes;                               // receieve data buffer


        /**
         *  @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);
            }
        }
예제 #36
0
        public void Dispose()
        {
            lock (_Lock)
            {
                if (TokenSource != null)
                {
                    if (!TokenSource.IsCancellationRequested)
                    {
                        TokenSource.Cancel();
                    }
                    TokenSource.Dispose();
                    TokenSource = null;
                }

                if (_SslStream != null)
                {
                    _SslStream.Close();
                    _SslStream.Dispose();
                    _SslStream = null;
                }

                if (_NetworkStream != null)
                {
                    _NetworkStream.Close();
                    // _NetworkStream.Dispose();
                    // _NetworkStream = null;
                }

                if (_TcpClient != null)
                {
                    _TcpClient.Close();
                    _TcpClient.Dispose();
                    _TcpClient = null;
                }
            }
        }
예제 #37
0
        /// <summary>
        /// Establish the TCP connection
        /// </summary>
        /// <param name="keepalive">Wether the connection should be kept alive after a first message</param>
        /// <returns>True for success, False otherwise</returns>
        public override bool Connect(bool keepalive = true)
        {
            try
            {
                // connect socket
                connection = new System.Net.Sockets.TcpClient();
                connection.ReceiveTimeout = 2000;
                connection.Connect(EndPoint);
                System.IO.Stream connectionStream = connection.GetStream();

                Stream = new IpcStream(connectionStream, KnownTypes, Encryptor);
            } catch (SocketException e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                return(false);
            }

            if (keepalive)
            {
                StartPing();
            }

            return(true);
        }
예제 #38
0
    public void connectToBot()
    {
        clientSocket = new System.Net.Sockets.TcpClient();
        log.logMsg(log.messages[0], log.normalColor);
        try
        {
            clientSocket.Connect(BotIP, BotPort);
            stream = clientSocket.GetStream();
        }
        catch (SocketException e)
        {
            log.logMsg(log.messages[3], log.warningColor);
            // Debug.Log(e.Message);
            connectedFalse();
        }

        if (clientSocket != null && clientSocket.Connected)
        {
            mjpeg.streamAddress = "http://" + BotIP + ":" + BotCameraPort.ToString() + "/stream.mjpg";
            connectedTrue();
            log.logMsg(log.messages[1], log.normalColor);
            log.inputKeyboardSelected();
        }
    }
예제 #39
0
    private void BeginAcceptTcpClient(IAsyncResult ar)
    {
        try
        {
            System.Net.Sockets.TcpClient tcpClient = NetworkListener.EndAcceptTcpClient(ar);
            Log.Info(string.Format("新链接:{0}", tcpClient.Client.RemoteEndPoint));
            NetBase netBase = new NetBase(1, 3, NetWorkType.Tcp);
            netBase.SetBuffer(100, 10);
            netBase.StartRecv(tcpClient.Client, handlers);

            JoinClient client = new JoinClient();
            client.net  = netBase;
            client.time = DateTime.Now.Ticks;
            lock (clients_add_obj)
            {
                clients_add.Add(client);
            }
        }
        catch (Exception ex)
        {
            Log.Error("BeginAcceptTcpClient Error:" + ex);
        }
        NetworkListener.BeginAcceptTcpClient(new AsyncCallback(this.BeginAcceptTcpClient), (object)null);
    }
예제 #40
0
        public string SendAndReceive(string message)
        {
            lock (_dataLockObject)
            {
                if (_dataClient == null)
                {
                    _dataClient = new System.Net.Sockets.TcpClient();

                    _dataClient.Connect(_host, _dataPort);

                    _dataStream = OnPrepareStream(_dataClient.GetStream());
                }

                message = PrepareOutgoingMessage(message);

                var success = TcpProtocolHelper.Write(_dataStream, message);
                if (!success)
                {
                    return(null);
                }

                return(PrepareIncommingMessage(TcpProtocolHelper.Read(_dataStream)));
            }
        }
예제 #41
0
        public static void Connect(string ip_port)
        {
            if (isConnected == false)
            {
                try
                {
                    string ip   = ip_port.Split(':')[0];
                    int    port = int.Parse(ip_port.Split(':')[1]);

                    logger.Info("Connecting to " + ip_port);
                    clientSocket = new System.Net.Sockets.TcpClient();

                    clientSocket.BeginConnect(ip, port, new AsyncCallback(ConnectCallback), clientSocket.Client);
                    logger.Info("Connected to " + ip_port);

                    iSAPPRemoteUI.updater.Start();
                    iSAPPRemoteUI.SetServerStatText("Server stats loading...");
                }
                catch (Exception ex)
                {
                    logger.Error(ex, ex.Message);
                }
            }
        }
예제 #42
0
        static void Main(string[] args)
        {
            //Connect to NATS Server using TCPClient.
            using (var tcp = new System.Net.Sockets.TcpClient())
            {
                tcp.Connect(NatsHost, NatsPort);

                while (true)
                {
                    Console.WriteLine("Send: (Blank to Exit)");

                    var message = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(message))
                    {
                        break;
                    }

                    //Use extension method below to send message
                    tcp.Client.Publish(Subject, message);
                }

                tcp.Close();
            }
        }
예제 #43
0
        private void Run()
        {
            Task.Run(async() =>
            {
                try
                {
                    using (_remoteClient)
                        using (client)
                        {
                            await client.ConnectAsync(_remoteServer.Address, _remoteServer.Port);
                            var serverStream = client.GetStream();
                            var remoteStream = _remoteClient.GetStream();

                            await Task.WhenAny(remoteStream.CopyToAsync(serverStream), serverStream.CopyToAsync(remoteStream));
                        }
                }
                catch (Exception) { }
                finally
                {
                    Console.WriteLine($"Closed {_clientEndpoint} => {_remoteServer}");
                    _remoteClient = null;
                }
            });
        }
예제 #44
0
        public async Task ConnectAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                //Connect async method
                await Close();

                cancellationToken.ThrowIfCancellationRequested();
                _client = new System.Net.Sockets.TcpClient();
                cancellationToken.ThrowIfCancellationRequested();
                await _client.ConnectAsync(_server, _port);
                await CloseIfCanceled(cancellationToken);

                // get stream and do SSL handshake if applicable

                _stream = _client.GetStream();
                await CloseIfCanceled(cancellationToken);
            }
            catch (Exception e)
            {
                CloseIfCanceled(cancellationToken).Wait();
                throw;
            }
        }
예제 #45
0
        void WaitForMessages()
        {
            while (client.Connected)
            {
                string msg = ReadNetStream(client.GetStream(), 2048);

                if (String.IsNullOrEmpty(msg))
                {
                    client.Close();
                }
                else if (msg != "\n")
                {
                    if (msg.EndsWith("\n"))
                    {
                        msg = msg.Remove(msg.Length - 1, 1);
                    }

                    form.JS("TcpClientHelper.ondatareceived('" + this.ID.ToString() + "', '" + msg.Replace("\\", "\\\\").Replace("'", "\\'") + "');");
                }
            }
            Console.WriteLine("disconnected");
            form.JS("TcpClientHelper.ondisconnected('" + this.ID.ToString() + "');");
            client = null;
        }
예제 #46
0
        public static void Main()
        {
            try
            {
                var i      = 0;
                var client = new System.Net.Sockets.TcpClient();
                client.Connect(Dns.GetHostName(), 2055);
                var stream = client.GetStream();
                while (i < 3)
                {
                    const string message = "client1 ";
                    var          data    = System.Text.Encoding.ASCII.GetBytes(message);
                    stream.Write(data, 0, data.Length);
                    Console.WriteLine("Sent: {0}", message);
                    data = new byte[256];
                    var bytes        = stream.Read(data, 0, data.Length);
                    var responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    Console.WriteLine("Received: {0}", responseData);
                    i++;
                }

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

            Console.WriteLine("\n Press Enter to continue...");
            Console.ReadLine();
        }
예제 #47
0
            /// <summary>
            /// send message to others
            /// </summary>
            /// <param name="destinationIP">the destination ip ,e.g.,192.168.1.1</param>
            /// <param name="msg">message you want to send</param>
            public static void SendMessage(string destinationIP, string msg)
            {
                System.Net.Sockets.TcpClient     tcpClient = null;
                System.Net.Sockets.NetworkStream netStream = null;
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
                var    destIP = System.Net.IPAddress.Parse(destinationIP);
                var    myIP   = Communication.GetLocalIP();
                //var myIP = "192.10.110.54";
                var epDest = new System.Net.IPEndPoint(destIP, 1124);

                Random ro       = new Random();
                int    up       = 1150;
                int    down     = 1123;
                var    sendport = 1123;

                while (!FunctionUtils.checkPort(sendport.ToString()))//检查端口占用
                {
                    sendport = ro.Next(down, up);
                }
                var dpLocal = new System.Net.IPEndPoint(myIP, sendport);

                tcpClient = new System.Net.Sockets.TcpClient(dpLocal);
                tcpClient.Connect(epDest);

                netStream = tcpClient.GetStream();
                if (netStream.CanWrite)
                {
                    netStream.Write(buffer, 0, buffer.Length);
                }
                tcpClient.GetStream().Close();
                tcpClient.Client.Close();
                tcpClient.Close();
                // tcpClient.GetStream().Close();
                // tcpClient.Client.Disconnect(false);
                //tcpClient.Close();
            }
예제 #48
0
        /// <summary>
        /// Connects to the remote server.
        /// </summary>
        /// <param name="server">Server data</param>
        /// <param name="lookForBackups">If false, no connection to backup servers will be made</param>
        private void Connect(Server server, bool lookForBackups = true)
        {
            this.server    = server;
            this.apiSocket = new System.Net.Sockets.TcpClient();

            bool connectionAttempted = false;

            while (!connectionAttempted || !apiSocket.Connected)
            {
                // Try to connect asynchronously and wait for the result
                IAsyncResult result = apiSocket.BeginConnect(this.server.Address, this.server.MainPort, null, null);
                connectionAttempted = result.AsyncWaitHandle.WaitOne(TIMEOUT, true);

                // If connection attempt failed (timeout) or not connected
                if (!connectionAttempted || !apiSocket.Connected)
                {
                    apiSocket.Close();
                    if (lookForBackups)
                    {
                        this.server = Servers.GetBackup(this.server);
                        apiSocket   = new System.Net.Sockets.TcpClient();
                    }
                    else
                    {
                        throw new APICommunicationException("Cannot connect to: " + server.Address + ":" + server.MainPort);
                    }
                }
            }

            if (server.Secure)
            {
                SslStream sl = new SslStream(apiSocket.GetStream(), false, new RemoteCertificateValidationCallback(SSLHelper.TrustAllCertificatesCallback));

                //sl.AuthenticateAsClient(server.Address);

                bool authenticated = ExecuteWithTimeLimit.Execute(TimeSpan.FromMilliseconds(5000), () =>
                {
                    sl.AuthenticateAsClient(server.Address, new X509CertificateCollection(), System.Security.Authentication.SslProtocols.Default, false);
                });

                if (!authenticated)
                {
                    throw new APICommunicationException("Error during SSL handshaking (timed out?)");
                }

                apiWriteStream = new StreamWriter(sl);
                apiReadStream  = new StreamReader(sl);
            }
            else
            {
                NetworkStream ns = apiSocket.GetStream();
                apiWriteStream = new StreamWriter(ns);
                apiReadStream  = new StreamReader(ns);
            }

            this.apiConnected = true;

            if (OnConnected != null)
            {
                OnConnected.Invoke(this.server);
            }


            this.streamingConnector = new StreamingAPIConnector(this.server);
        }
예제 #49
0
        private async void AcceptConnections()
        {
            while (!_Token.IsCancellationRequested)
            {
                ClientMetadata client = null;

                try
                {
                    System.Net.Sockets.TcpClient tcpClient = await _Listener.AcceptTcpClientAsync();

                    string clientIp = tcpClient.Client.RemoteEndPoint.ToString();

                    client = new ClientMetadata(tcpClient);

                    if (_Ssl)
                    {
                        if (AcceptInvalidCertificates)
                        {
                            client.SslStream = new SslStream(client.NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                        }
                        else
                        {
                            client.SslStream = new SslStream(client.NetworkStream, false);
                        }

                        bool success = await StartTls(client);

                        if (!success)
                        {
                            client.Dispose();
                            continue;
                        }
                    }

                    lock (_Clients)
                    {
                        _Clients.Add(clientIp, client);
                    }

                    Logger?.Invoke("Starting connection monitor for: " + clientIp);
                    Task unawaited = Task.Run(() => ClientConnectionMonitor(client), client.Token);
                    ClientConnected?.Invoke(this, new ClientConnectedEventArgs(clientIp));
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (ObjectDisposedException)
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                    continue;
                }
                catch (Exception e)
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                    Logger?.Invoke(_Header + "Exception while awaiting connections: " + e.ToString());
                    continue;
                }
            }

            _IsListening = false;
        }
예제 #50
0
        private bool ReportToZhuZhan(Stopwatch watch, Socket socket)
        {
            watch.Start();
            DataItem_C001 item_C001 = new DataItem_C001(ser++, DateTime.Now, this.TotalAmount, this.TotalTopUp - this.CurrentBalance, this.CurrentBalance, this.LastTotal, this._st1, this._st2);
            TaskArge      taskArge  = new TaskArge(this.Mac, item_C001, ControlCode.CTR_6, MKey);
            Frame         frame     = new Frame(taskArge);
            int           iTime     = 1;

            byte[] buffer = frame.GetBytes();
            while (socket.Poll(100, SelectMode.SelectWrite))
            {
                socket.Send(buffer);
                break;
            }
            Notice(string.Format("{1:yyyy-MM-dd HH:mm:ss} 第{0}次发送上报数据请求帧\r", iTime, DateTime.Now));

            string message;

            //等待应答
            while (true)
            {
                Thread.Sleep(100);
                if (socket.Poll(10, SelectMode.SelectRead))
                {
                    int dLength = socket.Available;
                    Thread.Sleep(100);
                    if (dLength != socket.Available)
                    {
                        dLength = socket.Available;
                    }
                    buffer = new byte[dLength];
                    socket.Receive(buffer);
                    Notice(string.Format("{1:yyyy-MM-dd HH:mm:ss}接收到主站应答数据:{0}\r", MyDataConvert.BytesToHexStr(buffer), DateTime.Now));

                    taskArge = JieXi(buffer, out message);
                    if (taskArge != null && taskArge.ControlCode == ControlCode.CTR_7)
                    {
                        Notice(string.Format("第{0}次发送上报数据请求完成。\r", iTime));
                    }
                    Notice(string.Format("本次上报数据总用时:{0}毫秒\r", watch.ElapsedMilliseconds));
                    this._reportWatch.Restart();
                    break;
                }
                else if (socket.Poll(100, SelectMode.SelectError))
                {
                }
                if (watch.ElapsedMilliseconds >= 1000 * 10)
                {
                    if (iTime >= 3)
                    {
                        //接收不到主站应答,本次上报结束
                        this.tcpClient.Close();
                        this.tcpClient = null;
                        return(false);
                    }
                    iTime++;
                    buffer = frame.GetBytes();
                    socket.Send(buffer);
                    Notice(string.Format("{1:yyyy-MM-dd HH:mm:ss}接收到主站应答数据:{0}\r", MyDataConvert.BytesToHexStr(buffer), DateTime.Now));
                    watch.Restart();
                }
            }

            return(true);
        }
예제 #51
0
        static public void Run()
        {
            Console.WriteLine("IP:");
            string ipStr = Console.ReadLine();

            IPAddress ip;

            if (!IPAddress.TryParse(ipStr, out ip))
            {
                Console.WriteLine("IP地址[{0}]无效。", ipStr);
                return;
            }


            Console.WriteLine("Port:");
            string portStr = Console.ReadLine();
            ushort port;

            if (!ushort.TryParse(portStr, out port))
            {
                Console.WriteLine("端口[{0}]无效。", portStr);
                return;
            }

            IPEndPoint endPoint = new IPEndPoint(ip, port);

            System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(AddressFamily.InterNetwork);
            try
            {
                Console.WriteLine("正在连接[{0}:{1}]...", ip, port);
                tcpClient.Connect(endPoint);
            }
            catch (SocketException se)
            {
                Console.WriteLine("连接失败:" + se.SocketErrorCode.ToString());
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("连接失败:" + e.Message);
                return;
            }

            NetworkStream ns = null;

            while (true)
            {
                if (ns == null)
                {
                    ns = tcpClient.GetStream();
                }

                Console.WriteLine("请输入信息:");
                string msg          = Console.ReadLine();
                byte[] msgByte      = System.Text.Encoding.UTF8.GetBytes(msg);
                byte[] msgByte_send = new byte[msgByte.Length + 1];
                for (int i = 0; i < msgByte.Length; i++)
                {
                    msgByte_send[i] = msgByte[i];
                }
                msgByte_send[msgByte_send.Length - 1] = 0;
                try
                {
                    //ns = tcpClient.GetStream();
                    ns.Write(msgByte_send, 0, msgByte_send.Length);
                    ns.Flush();
                }
                catch (SocketException se)
                {
                    Console.WriteLine("发送消息失败:" + se.SocketErrorCode.ToString());
                    return;
                }
                catch (Exception e)
                {
                    Console.WriteLine("发送消息失败:" + e.Message);
                    return;
                }

                Console.WriteLine("");
                Console.WriteLine("正在等待接收信息...");

                byte[] recMsgByte = new byte[4096];
                int    recLen;
                try
                {
                    //ns = tcpClient.GetStream();
                    recLen = ns.Read(recMsgByte, 0, recMsgByte.Length);
                }
                catch (SocketException se)
                {
                    Console.WriteLine("接收消息失败:" + se.SocketErrorCode.ToString());
                    return;
                }
                catch (Exception e)
                {
                    Console.WriteLine("接收消息失败:" + e.Message);
                    return;
                }

                string recMsg = System.Text.Encoding.UTF8.GetString(recMsgByte, 0, recLen);
                Console.WriteLine(recMsg);
                Console.WriteLine("");

                //int int32 = BitConverter.ToInt32(recMsgByte, 0);
                //string hexStr = "0x" + Convert.ToString(int32, 16);

                //Console.WriteLine(hexStr);

                if (Console.KeyAvailable)
                {
                    break;
                }
            }
        }
예제 #52
0
        public void StartTask(FileTransportTask task) //Sender
        {
            if (task == null)
            {
                throw new ArgumentNullException("task");
            }
            if (task.State != FileTransportState.Waiting)
            {
                throw new ArgumentException();
            }
            Tasks.Add(task);
            var t = new Task(() =>
            {
                #region Daten verkleinern nur ohne Datasets
                if (CompressBytes && task.DatasetCount == 0)
                {
                    task.State = FileTransportState.CompressBytes;
                    using (var m = new MemoryStream())
                        using (var comp = new DeflateStream(m, CompressionMode.Compress))
                            using (var r = new BinaryReader(m))
                                using (var w = new BinaryWriter(comp))
                                {
                                    w.Write(task.Data);
                                    m.Position           = 0;
                                    task.CompressedBytes = r.ReadBytes((int)m.Length);
                                }
                }
                else
                {
                    task.CompressedBytes = task.Data;
                }
                task.Size = task.CompressedBytes.Length;
                #endregion
                //Verbinden
                task.State     = FileTransportState.WaitForLocalConnector;
                Connection con = null;
                if (Role == ServerClientRole.Server)
                {
                    con = FindEmptyConnection();
                    while (con == null)
                    {
                        System.Threading.Thread.Sleep(10);
                        con = FindEmptyConnection();
                    }
                    SetUsedState(con, true);
                    task.Connection = con;
                }
                task.State = FileTransportState.ConnectToServer;
                Action act = null;
                act        = new Action(() =>
                {
                    if (task.State == FileTransportState.Transport && task.TransportedBytes == 0)
                    {
                        TcpClient tcp      = null;
                        TcpListener server = null;
                        if (Role == ServerClientRole.Server)
                        {
                            server = new TcpListener(IPAddress.Any, con.Port);
                            server.Start();
                            tcp = server.AcceptTcpClient();
                            server.Stop();
                            server = null;
                        }
                        else
                        {
                            tcp = new System.Net.Sockets.TcpClient();
                            tcp.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(task.Connection.Target), task.Connection.Port));
                        }

                        var stream = tcp.GetStream();

                        if (task.DatasetCount == 0)
                        {
                            var offset = 0;
                            while (offset < task.CompressedBytes.Length)
                            {
                                stream.Write(task.CompressedBytes, offset, Math.Min(task.CompressedBytes.Length - offset, tcp.SendBufferSize));
                                System.Threading.Thread.Sleep(1);
                                offset += tcp.SendBufferSize;
                                task.TransportedBytes = Math.Min(task.CompressedBytes.Length, offset);
                                task.OnServerStateUpdated();
                            }
                        }
                        else
                        {
                            for (task.CurrentDataset = 0; task.CurrentDataset < task.DatasetCount; ++task.CurrentDataset)
                            {
                                var bytes      = task.OnGetDatasetData(task.CurrentDataset);
                                var datalength = BitConverter.GetBytes(bytes.Length);
                                stream.Write(datalength, 0, datalength.Length);
                                var offset            = 0;
                                task.Size             = bytes.Length;
                                task.TransportedBytes = 0;
                                while (offset < bytes.Length)
                                {
                                    if (!tcp.Connected)
                                    {
                                        break;
                                    }
                                    stream.Write(bytes, offset, Math.Min(bytes.Length - offset, tcp.SendBufferSize));
                                    System.Threading.Thread.Sleep(1);
                                    offset += tcp.SendBufferSize;
                                    task.TransportedBytes = Math.Min(bytes.Length, offset);
                                    task.OnServerStateUpdated();
                                }
                                if (!tcp.Connected)
                                {
                                    break;
                                }
                            }
                        }

                        tcp.Close();
                        task.State = FileTransportState.Finished;
                        Tasks.Remove(task);
                        task.OnServerStateUpdated();
                        task.ServerStateUpdated -= act;
                        if (con != null)
                        {
                            SetUsedState(con, false);
                        }
                    }
                });
                task.ServerStateUpdated += act;
                var mes         = new PrimaryMessage();
                var ftd         = new FileTransportData();
                ftd.TransportID = task.ID;
                ftd.SenderID    = Manager.CurrentId.Id;
                ftd.Type        = FileTransportType.WantSendFile;
                ftd.Size        = task.Size;
                ftd.Datasets    = task.DatasetCount;
                ftd.Connection  = task.Connection;
                mes.ClientData.SetSerializeAble(ftd);
                mes.MessageType            = PrimaryMessageType.FileTransportServerToClient;
                mes.MessageRoot.Connection = task.TargetUser.DefaultConnection;
                mes.MessageRoot.Connector  = task.TargetUser.DefaultConnector;
                mes.MessageRoot.RemoteId   = task.TargetUser.Id;
                Manager.SendMessage(mes);
            });

            t.Start();
        }
예제 #53
0
        public RecievePacket handleData(System.IO.BinaryReader br, System.IO.BinaryWriter bw, System.Net.Sockets.TcpClient client)
        {
            double        server = br.ReadDouble();
            List <object> l      = new List <object>();

            l.Add(server);
            return(new RecievePacket(l));
        }
예제 #54
0
 public void Connect(string ip, int port)
 {
     _client = new TcpClient();
     _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
     _client.Connect(IPAddress.Parse(ip), port);
 }
예제 #55
0
        //Semaphore _semaphore = new Semaphore(10, 10);

        /// <summary>
        /// 上报数据并接收主站指令
        /// </summary>
        private void ReportData()
        {
            //FE FE 68 30 39 61 51 23 35 51 04 21 1E C0 01 20 40 14 16 22 04 15 20 18 56 42 37 18 56 02 00 18 56 02 00 18 56 02 00 23 00 00 00 6F 16
            DataItem_C001 item_C001 = new DataItem_C001(ser++, DateTime.Now, this.TotalAmount, LJMoney, CurrentBalance, this.LastTotal, _st1, _st2);
            TaskArge      taskArge  = new TaskArge(this.Mac, item_C001, ControlCode.CTR_6, MKey);
            //连接服务器
            Stopwatch watch = new Stopwatch();

            watch.Start();
            byte[] buffer = null;
            try
            {
                this.tcpClient = new System.Net.Sockets.TcpClient();
                this.tcpClient.Connect(this.hostname, this.port);
                Socket socket = tcpClient.Client;
                Notice(string.Format("{0} 表连接服务器完成.\r", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                if (!ReportToZhuZhan(watch, socket))
                {
                    return;
                }

                Frame  frame = new Frame(taskArge);
                string message;

                //等待主站指令
                Notice(string.Format("================================\r"));

                watch.Restart();
                while (true)
                {
                    if (watch.ElapsedMilliseconds >= 1000 * 20)
                    {
                        //20秒内没有收到任何主站指令,关闭连接并结束本次通信
                        this.tcpClient.Close();
                        Notice(string.Format("{0} 关闭表连接\r\n--------------------------------\r", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                        this._reportWatch.Restart();
                        break;
                    }
                    //if (this._reportWatch.ElapsedMilliseconds >= this.周期 * 60 * 1000)
                    //{
                    //    //上报数据周期到
                    //    watch.Restart();
                    //    if (!ReportToZhuZhan(watch,socket))
                    //    {
                    //        return;
                    //    }
                    //}
                    //检查数据
                    if (socket.Poll(10, SelectMode.SelectRead))
                    {
                        int dLength = socket.Available;
                        Thread.Sleep(100);
                        if (dLength != socket.Available)
                        {
                            dLength = socket.Available;
                        }
                        buffer = new byte[dLength];
                        socket.Receive(buffer);
                        Notice(string.Format("{1:yyyy-MM-dd HH:mm:ss} 接收到主站数据:{0}\r", MyDataConvert.BytesToHexStr(buffer), DateTime.Now));
                        Thread.Sleep(10);
                        // _semaphore.WaitOne();
                        //解析接收到的数据
                        try
                        {
                            taskArge = JieXi(buffer, out message);
                            //  _semaphore.Release();
                            Notice(string.Format("控制码:{0} 指令:{1}\r", taskArge.ControlCode, taskArge.Data.IdentityCode));
                        }
                        catch (Exception ex)
                        {
                            // _semaphore.Release();
                            throw ex;
                        }

                        if (taskArge != null && (((byte)taskArge.ControlCode) & 0x80) == 0x00)
                        {
                            //接收到主站请求数据
                            taskArge = CreateAnswerData(taskArge);
                            frame    = new Frame(taskArge);
                            buffer   = frame.GetBytes();
                            socket.Send(buffer);
                            Notice(string.Format("{0:yyyy-MM-dd HH:mm:ss}从站应答完成。\r", DateTime.Now));
                            watch.Restart();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Notice(string.Format("{1:yyyy-MM-dd HH:mm:ss} 程序异常:{0}\r", e.Message, DateTime.Now));

                Debug.Print(e.Message);
            }
        }
예제 #56
0
        private void _ReadThreadFunction(object obj)
        {
            SocketClient c = (SocketClient)obj;

            try
            {
                _evtStartRead.WaitOne();
                NetworkStream nStream = c._Client.GetStream();
                while (c._Client.Connected)
                {
                    if (c._Client.Available == 0)
                    {
                        Thread.Sleep(100);

                        bool b = !(c._Client.Client.Poll(1, SelectMode.SelectRead) && c._Client.Available == 0);
                        if (b == false)
                        {
                            break;
                        }
                        continue;
                    }
                    if (nStream.CanRead)
                    {
                        int iReadLen = 0;
                        int toRead   = c._Client.Available;
                        if (toRead == 0)
                        {
                            toRead = c._Client.ReceiveBufferSize;
                        }
                        byte[] myReadBuffer = new byte[c._Client.Available];

                        iReadLen = nStream.Read(myReadBuffer, 0, myReadBuffer.Length);

                        if (iReadLen != 0)
                        {
                            if (c.OnDataReceived != null)
                            {
                                c.OnDataReceived(c, myReadBuffer);
                            }
                        }
                        //nStream.BeginRead(myReadBuffer,
                        //                    0,
                        //                    myReadBuffer.Length,
                        //                    new AsyncCallback(_ReadCallback),
                        //                    c);

                        //c._evtReadDone.WaitOne();
                    }
                    else
                    {
                        Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
                    }
                }
            }
            catch (NullReferenceException ex)
            {
                Debug.WriteLine(ex.Message);
            }
            catch (ObjectDisposedException ex)
            {
                Debug.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (OnDisconnected != null)
                {
                    OnDisconnected(this);
                }

                if (_Client != null)
                {
                    _Client.Close();
                    _Client = null;
                }
            }
        }
예제 #57
0
        private async void AcceptConnections()
        {
            while (!_Token.IsCancellationRequested)
            {
                ClientMetadata client = null;

                try
                {
                    System.Net.Sockets.TcpClient tcpClient = await _Listener.AcceptTcpClientAsync();

                    string clientIp = tcpClient.Client.RemoteEndPoint.ToString();

                    client = new ClientMetadata(tcpClient);

                    if (_Ssl)
                    {
                        if (AcceptInvalidCertificates)
                        {
                            client.SslStream = new SslStream(client.NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                        }
                        else
                        {
                            client.SslStream = new SslStream(client.NetworkStream, false);
                        }

                        bool success = await StartTls(client);

                        if (!success)
                        {
                            client.Dispose();
                            continue;
                        }
                    }

                    _Clients.TryAdd(clientIp, client);
                    _ClientsLastSeen.TryAdd(clientIp, DateTime.Now);
                    Logger?.Invoke("[SimpleTcp.Server] Starting data receiver for: " + clientIp);
                    ClientConnected?.Invoke(this, new ClientConnectedEventArgs(clientIp));
                    Task unawaited = Task.Run(() => DataReceiver(client), _Token);
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (ObjectDisposedException)
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                    continue;
                }
                catch (Exception e)
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                    Logger?.Invoke("[SimpleTcp.Server] Exception while awaiting connections: " + e.ToString());
                    continue;
                }
            }
        }
예제 #58
0
 protected ConnectionBase(IMessageSink messageSink)
 {
     this.messageSink = messageSink;
     this.client      = new TcpClient();
 }
        private void ClientConnected(object sender, System.Net.Sockets.TcpClient e)
        {
            Console.WriteLine("Client connected");

            clients.Add(e.Client);
        }
예제 #60
0
        public void ServerThreadProc()
        {
            while (true)
            {
                try
                {
                    // 處理用戶端連線
                    tcpClient = tcpListener.AcceptTcpClient();

                    // 取得本機相關的網路資訊
                    IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint;

                    // 以Client屬性取得用戶端之Socket物件
                    Socket clientSocket = tcpClient.Client;

                    // 取得連線用戶端相關的網路連線資訊
                    IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint;

                    Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString());
                    Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString());

                    // 取得伺服端的輸出入串流
                    NetworkStream networkStream = tcpClient.GetStream();

                    // 判斷串流是否支援讀取功能
                    if (networkStream.CanRead)
                    {
                        byte[] bytes         = new byte[1024];
                        int    bytesReceived = 0;
                        string data          = null;

                        do
                        {
                            // 自資料串流中讀取資料
                            bytesReceived = networkStream.Read(bytes, 0, bytes.Length);

                            data += Encoding.ASCII.GetString(bytes, 0, bytesReceived);
                        } while (networkStream.DataAvailable); // 判斷串流中的資料是否可供讀取

                        Console.WriteLine("接收的資料內容: " + "\r\n" + "{0}", data + "\r\n");
                    }
                    else
                    {
                        Console.WriteLine("串流不支援讀取功能.");
                    }

                    // 判斷串流是否支援寫入功能
                    if (networkStream.CanWrite)
                    {
                        // 測試用
                        string htmlBody   = "<html><head><title>Send Test</title></head><body><font size=2 face=Verdana>Sent OK.</font></body></html>";
                        string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" + "Server: HTTP Server 1.0" + "\r\n" + "Content-Type: text/html" + "\r\n" + "Content-Length: " + htmlBody.Length + "\r\n" + "\r\n";

                        string htmlContent = htmlHeader + htmlBody;

                        // 設定傳送資料緩衝區
                        byte[] msg = Encoding.ASCII.GetBytes(htmlContent);

                        // 將資料寫入資料串流中
                        networkStream.Write(msg, 0, msg.Length);

                        Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", Encoding.UTF8.GetString(msg, 0, msg.Length) + "\r\n");
                    }
                    else
                    {
                        Console.WriteLine("串流不支援寫入功能.");
                    }

                    // 關閉串流
                    networkStream.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }