示例#1
2
        public void TryPrint(string zplCommands)
        {
            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(this.m_IPAddress, this.m_Port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(zplCommands);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                this.m_ErrorCount += 1;
                if(this.m_ErrorCount < 10)
                {
                    System.Threading.Thread.Sleep(5000);
                    this.TryPrint(zplCommands);
                }
                else
                {
                    throw ex;
                }
            }
        }
        public static string connect(String server,int port,String ouath)
        {
            System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient ();
            sock.Connect (server, port);
            if (!sock.Connected) {
                Console.Write ("not working hoe");

            }
            System.IO.TextWriter output;
            System.IO.TextReader input;
            output = new System.IO.StreamWriter (sock.GetStream ());
            input = new System.IO.StreamReader (sock.GetStream ());
            output.Write (

                "PASS " + ouath + "\r\n" +
                "NICK " + "Sail338" + "\r\n" +
                "USER " + "Sail338" + "\r\n" +
                "JOIN " 	+ "#sail338" + "" + "\r\n"

            );
            output.Flush ();

            for (String rep = input.ReadLine ();; rep = input.ReadLine ()) {
                string[] splitted = rep.Split (':');
                if (splitted.Length > 2) {
                    string potentialVote = splitted [2];
                    if (Array.Exists (validVotes, vote => vote.Equals(potentialVote)))
                        return potentialVote;
                }
            }
        }
		/*
		* 
		*/
		public virtual void  openSocket()
		{
			socket = new System.Net.Sockets.TcpClient(host, port);
			socket.LingerState = new System.Net.Sockets.LingerOption(true, 1000);
			
			os = socket.GetStream();
			is_Renamed = socket.GetStream();
		}
 public TcpConnection(System.Net.Sockets.TcpClient socket)
 {
     if (socket == null)
         throw new System.NullReferenceException();
     this.socket = socket;
     in_stream = new System.IO.StreamReader(socket.GetStream());
     out_stream = new System.IO.StreamWriter(socket.GetStream());
 }
        public static string PerformWhois(string WhoisServerHost, int WhoisServerPort, string Host)
        {
            string result="";
            try {
                String strDomain = Host;
                char[] chSplit = {'.'};
                string[] arrDomain = strDomain.Split(chSplit);
                // There may only be exactly one domain name and one suffix
                if (arrDomain.Length != 2) {
                    return "";
                }

                // The suffix may only be 2 or 3 characters long
                int nLength = arrDomain[1].Length;
                if (nLength != 2 && nLength != 3) {
                    return "";
                }

                System.Collections.Hashtable table = new System.Collections.Hashtable();
                table.Add("de", "whois.denic.de");
                table.Add("be", "whois.dns.be");
                table.Add("gov", "whois.nic.gov");
                table.Add("mil", "whois.nic.mil");

                String strServer = WhoisServerHost;
                if (table.ContainsKey(arrDomain[1])) {
                    strServer = table[arrDomain[1]].ToString();
                }
                else if (nLength == 2) {
                    // 2-letter TLD's always default to RIPE in Europe
                    strServer = "whois.ripe.net";
                }

                System.Net.Sockets.TcpClient tcpc = new System.Net.Sockets.TcpClient ();
                tcpc.Connect(strServer, WhoisServerPort);
                String strDomain1 = Host+"\r\n";
                Byte[] arrDomain1 = System.Text.Encoding.ASCII.GetBytes(strDomain1.ToCharArray());
                System.IO.Stream s = tcpc.GetStream();
                s.Write(arrDomain1, 0, strDomain1.Length);
                System.IO.StreamReader sr = new System.IO.StreamReader(tcpc.GetStream(), System.Text.Encoding.ASCII);
                System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
                string strLine = null;
                while (null != (strLine = sr.ReadLine())) {
                    strBuilder.Append(strLine+"\r\n");
                }
                result = strBuilder.ToString();
                tcpc.Close();
            }catch(Exception exc) {
                result="Could not connect to WHOIS server!\r\n"+exc.ToString();
            }
            return result;
        }
		//UPGRADE_NOTE: Synchronized keyword was removed from method 'initSocket'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'"
		private void  initSocket()
		{
			lock (this)
			{
				if (socket == null)
				{
					socket = new System.Net.Sockets.TcpClient(host, port);
					outStream = socket.GetStream();
					inStream = socket.GetStream();
					oos = new System.IO.BinaryWriter(outStream);
					ois = new System.IO.BinaryReader(inStream);
				}
			}
		}
示例#7
0
        /// <summary>
        /// Constructs a Communicator. Automatically starts a thread for receiving from the client.
        /// </summary>
        /// <param name="connection">A client for the Communicator to connect with.</param>
        public Communicator(System.Net.Sockets.TcpClient connection)
        {
            client = connection;
            writer = new StreamWriter(client.GetStream());
            reader = new StreamReader(client.GetStream());

            authenticated = false;

            username = "";
            password = "";

            receiveMessage = new Thread(new ThreadStart(readMessage));
            receiveMessage.IsBackground = true;
        }
示例#8
0
        static void Main(string[] args)
        {
            Protocol protocol;
             string ip;
             int port;
             V2DLE dle;
             System.Net.Sockets.TcpClient tcp;
            protocol = new Protocol();
            protocol.Parse(System.IO.File.ReadAllText(Protocol.CPath(AppDomain.CurrentDomain.BaseDirectory+"TIME.txt")),false);
            ip = protocol.ip;
            port = protocol.port;

            while (true)
            {
                try
                {
                    bool isCommErr = false;
                    tcp = new System.Net.Sockets.TcpClient();
                    tcp = ConnectTask(ip, port);
                    dle = new V2DLE("DigitTimer", tcp.GetStream());
                    dle.OnCommError+=(s,a)=>
                        {
                            isCommErr = true;
                            dle.Close();
                        };
                    while (!isCommErr)
                    {

                        System.Data.DataSet ds = protocol.GetSendDataSet("report_system_time");
                        SendPackage pkg = protocol.GetSendPackage(ds, 0xffff);
                        pkg.cls = CmdClass.A;
                        dle.Send(pkg);
                        if (pkg.result == CmdResult.ACK)
                        {
                            System.Data.DataSet retDs = protocol.GetReturnDsByTextPackage(pkg.ReturnTextPackage);
                            int yr,mon,dy,hr,min,sec;
                            yr=System.Convert.ToInt32(retDs.Tables[0].Rows[0]["year"]);
                            mon = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["month"]);
                            dy = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["day"]);
                            hr = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["hour"]);
                            min = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["minute"]);
                            sec = System.Convert.ToInt32(retDs.Tables[0].Rows[0]["second"]);
                             DateTime dt = new DateTime(yr, mon, dy, hr, min, sec);
                             Console.WriteLine(dt.ToString());
                             RemoteInterface.Util.SetSysTime(dt);
                        }
                        else
                        {
                            Console.WriteLine(pkg.result.ToString());
                        }

                        System.Threading.Thread.Sleep(1000 * 60 );
                    }
                }
                catch (Exception ex)
                {
                    ;
                }
            }
        }
示例#9
0
        private void printButton_Click(object sender, EventArgs e)
        {
            // Printer IP Address and communication port
            string ipAddress = printerIpText.Text;
            int port = 9100;

            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(ipAddress, port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(zplCode);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
                MessageBox.Show("Print Successful!", "Success");
                this.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex);
                MessageBox.Show("No printer installed corresponds to the IP address given", "No response");
            }
        }
示例#10
0
 public static async Task<OpcWriter> CreateAsync(string host, int port = DefaultPort)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(host, port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
示例#11
0
 public TcpClient(string hostName, int port)
 {
     _buffer = new byte[ReadSize];
     _tcpClient = new System.Net.Sockets.TcpClient(hostName, port);
     if (_tcpClient.Connected)
         _stream = _tcpClient.GetStream();
 }
示例#12
0
 public static OpcWriter Create(string host, int port = DefaultPort)
 {
     var client = new System.Net.Sockets.TcpClient();
     client.Connect(host, port);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
示例#13
0
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>
        /// SocketException is resolved at higher level in the
        /// RemoteObjectProxyProvider.ProxyInterceptor.Intercept() method.
        /// </remarks>
        /// <param name="command"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="System.Net.Sockets.SocketException">
        /// When it is not possible to connect to the server.
        /// </exception>
        public string Request(string command, string[] data)
        {
            var client = new System.Net.Sockets.TcpClient(ServerAddress.IPAddress.ToString(), ServerAddress.Port);
            using (var clientStream = client.GetStream())
            {
                var sw = new StreamWriter(clientStream);

                command = command
                    .Replace("\r", TcpServer.CarriageReturnReplacement)
                    .Replace("\n", TcpServer.LineFeedReplacement);
                sw.WriteLine(command);

                sw.WriteLine(data.Length.ToString());
                foreach (string item in data)
                {
                    string encodedItem = item
                        .Replace("\r", TcpServer.CarriageReturnReplacement)
                        .Replace("\n", TcpServer.LineFeedReplacement);
                    sw.WriteLine(encodedItem);
                }

                sw.Flush();

                var sr = new StreamReader(clientStream);
                string result = sr.ReadLine();
                if (result != null)
                {
                    result = result
                        .Replace(TcpServer.CarriageReturnReplacement, "\r")
                        .Replace(TcpServer.LineFeedReplacement, "\n");
                }
                return result;
            }
        }
示例#14
0
        public bool Connect()
        {
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);

            if (objSck != null)
            {
                objSck.Close();
                objSck = null;
            }

            objSck = new System.Net.Sockets.TcpClient();

            try
            {
                objSck.Connect(ipAdd, port);
            }
            catch(Exception)
            {
                return false;
            }
            //catch (Exception)
            //{

            //    throw;
            //}

            //NetworkStreamを取得
            ns = objSck.GetStream();

            return true;
        }
示例#15
0
 public static async Task<OpcWriter> CreateAsync(IPEndPoint target)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(target.Address, target.Port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
示例#16
0
        /// <summary>
        /// Open 通信要求受付(非同期)
        /// </summary>
        /// <param name="ipAddr">IPアドレス</param>
        /// <param name="ipPort">ポート</param>
        /// <returns></returns>
        public async void OpenAsync()
        {
            sw.Start();

            //ListenするIPアドレス
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(listenIP);

            //TcpListenerオブジェクトを作成する
            listener =
                new System.Net.Sockets.TcpListener(ipAdd, listenPort);

            //Listenを開始する
            listener.Start();
            Console.WriteLine("Listenを開始しました({0}:{1})。",
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            //client = listener.AcceptTcpClient();
            try
            {
                client = await listener.AcceptTcpClientAsync();
                Console.WriteLine("クライアント({0}:{1})と接続しました。",
                    ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                    ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

                //NetworkStreamを取得
                ns = client.GetStream();
            }
            catch (Exception)
            {
            }
        }
示例#17
0
 public static OpcWriter Create(IPEndPoint target)
 {
     var client = new System.Net.Sockets.TcpClient();
     client.Connect(target.Address, target.Port);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
示例#18
0
 public Conexao(System.Net.Sockets.TcpClient client, Server server)
 {
     this.client = client;
     this.server = server;
     Stream s = client.GetStream();
     writer = new StreamWriter(s);
     reader = new StreamReader(s);
 }
        public bool client_coneciton()
        {
            client = new System.Net.Sockets.TcpClient(IP_add, port);
            ns = client.GetStream();
            ns.ReadTimeout = 10000;
            ns.WriteTimeout = 10000;

            return true;
        }
示例#20
0
 public MsgSource(int port)
 {
   this.port = port;
   Console.Write("Listening...");
   server = System.Net.Sockets.TcpListener.Create(port);
   server.Start();
   serverside_client = server.AcceptTcpClient();
   Console.WriteLine("\nClient connected");
   stream = serverside_client.GetStream();
 }
示例#21
0
 public void open(ConnectionData cnn)
 {
     //TcpClientを作成し、サーバーと接続する
     tcp = new System.Net.Sockets.TcpClient(cnn.addr, cnn.port);
     //NetworkStreamを取得する
     ns = tcp.GetStream();
     ns.WriteTimeout = 1;
     //
     isOpen = true;
 }
示例#22
0
 private void connectToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         mSocket = new System.Net.Sockets.TcpClient();
         mSocket.Connect(mSettings.Hostname, mSettings.Port);
         System.IO.StreamReader reader = new System.IO.StreamReader(mSocket.GetStream());
         string hello = reader.ReadLine();
         string[] data = hello.Split(' ');
         mCGEResX = Convert.ToInt32(data[1]);
         mCGEResY = Convert.ToInt32(data[2]);
         mSockStream = new System.IO.StreamWriter(mSocket.GetStream(), Encoding.GetEncoding(1252));
     }
     catch (System.Net.Sockets.SocketException)
     {
         mSocket = null;
         MessageBox.Show("Could not connect to CGE");
     }
 }
示例#23
0
 public TCPClient(string host, int port)
 {
     Hostname = host;
     TargetPort = port;
     Client = new System.Net.Sockets.TcpClient(host, port);
     ClientStream = Client.GetStream();
     Writer = new StreamWriter(ClientStream);
     Reader = new StreamReader(ClientStream);
     new Thread(ReceiveMessages).Start();
 }
示例#24
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            string host = textBox2.Text.Trim();
            int port = int.Parse(textBox3.Text);
            try
            {
                System.Net.Sockets.TcpClient tcp =
                  new System.Net.Sockets.TcpClient(host, port);

                System.Net.Sockets.NetworkStream ns = tcp.GetStream();

                string sendMsg = textBox1.Text;
                if (sendMsg == "" || textBox1.Text.Length > 140)
                {
                    textBlock1.Text = "ツイートできる条件を満たしてません!!";
                    tcp.Close();
                    return;
                }

                byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                ns.Write(sendBytes, 0, sendBytes.Length);

                //TCPソケットサーバーからストリームが送られてくる場合に受け取れるように
                if (checkBox1.IsChecked == true) {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                     byte[] resBytes = new byte[256];
                     int resSize;
                     do
                     {
                         resSize = ns.Read(resBytes, 0, resBytes.Length);
                         if (resSize == 0)
                         {
                             textBlock1.Text = "サーバーが切断しました。";
                             return;
                         }
                         ms.Write(resBytes, 0, resSize);
                     } while (ns.DataAvailable);//TODO:RubyのTCPSocketのputsメソッドに対応していない
                     string resMsg = enc.GetString(ms.ToArray());

                    textBlock1.Text = resMsg;
                    ms.Close();
                }
                ns.Close();
                tcp.Close();
                textBlock1.Text = host + "のmikutterでつぶやきました。";
                textBox1.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(),"Error");
                Environment.Exit(1);
            }
        }
示例#25
0
        //通信開始ボタン(待機状態に)
        private void button1_Click(object sender, EventArgs e)
        {
            if (socet == false)//つながってないなら
            {
                try
                {
                    //ListenするIPアドレス
                    //string ipString = "127.0.0.1";
                    string ipString = textBox3.Text;
                    System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

                    //ホスト名からIPアドレスを取得する時は、次のようにする
                    //string host = "localhost";
                    //System.Net.IPAddress ipAdd =
                    //    System.Net.Dns.GetHostEntry(host).AddressList[0];
                    //.NET Framework 1.1以前では、以下のようにする
                    //System.Net.IPAddress ipAdd =
                    //    System.Net.Dns.Resolve(host).AddressList[0];

                    //Listenするポート番号
                    int port = int.Parse(textBox4.Text);

                    //TcpListenerオブジェクトを作成する
                    listener = new System.Net.Sockets.TcpListener(ipAdd, port);

                    //Listenを開始する
                    listener.Start();
                    label1.Text = "Listenを開始しました(" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Address + ":" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Port + ")。";

                    //接続要求があったら受け入れる
                    client = listener.AcceptTcpClient();
                    label1.Text = "クライアント(" + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address + ":" + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port + ")と接続しました。";

                    //NetworkStreamを取得
                    ns = client.GetStream();

                    //読み取り、書き込みのタイムアウトを10秒にする
                    //デフォルトはInfiniteで、タイムアウトしない
                    //(.NET Framework 2.0以上が必要)
                    ns.ReadTimeout = 10000;
                    ns.WriteTimeout = 10000;
                    socet = true;
                }
                catch (FormatException)
                {
                    MessageBox.Show("IPアドレス、ポート番号を正しく入力してください(半角)", "エラー");
                }
                catch (System.Net.Sockets.SocketException ER)
                {
                    MessageBox.Show("IPアドレスが間違ってます。\ncmd.exeで調べてください\n(ipconfig)", "エラー");
                }
            }

           
        }
示例#26
0
文件: Client.cs 项目: rvnijnatten/IP2
        /// <summary>
        /// Generates a new instance
        /// </summary>
        /// <param name="pTcpClient"></param>
        public Client(System.Net.Sockets.TcpClient pTcpClient)
        {
            m_pTcpClient = pTcpClient;
            m_pWorkerThread = new System.Threading.Thread(workerThread);

            // Initialize the SSL connection
            m_pSslStream = new System.Net.Security.SslStream(m_pTcpClient.GetStream(), false);
            m_pSslStream.AuthenticateAsServer(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("Resources/Certificate.cer"), false, System.Security.Authentication.SslProtocols.Tls, false);

            m_pWorkerThread.Start();
        }
示例#27
0
			private void  Verify(sbyte message)
			{
				try
				{
					System.Net.Sockets.TcpClient s = new System.Net.Sockets.TcpClient(Enclosing_Instance.host, Enclosing_Instance.port);
					System.IO.Stream out_Renamed = s.GetStream();
					out_Renamed.WriteByte((byte) Enclosing_Instance.id);
					out_Renamed.WriteByte((byte) message);
					System.IO.Stream in_Renamed = s.GetStream();
					int result = in_Renamed.ReadByte();
					in_Renamed.Close();
					out_Renamed.Close();
					s.Close();
					if (result != 0)
						throw new System.SystemException("lock was double acquired");
				}
				catch (System.Exception e)
				{
					throw new System.SystemException(e.Message, e);
				}
			}
示例#28
0
        private void SendBytes(IPEndPoint endpoint, byte[] buffer)
        {
            using (var client = new System.Net.Sockets.TcpClient())
            {
                client.Connect(endpoint);

                var stream = client.GetStream();
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();

                client.Close();
            }
        }
示例#29
0
        public Communicator(System.Net.Sockets.TcpClient connection, WriteMessageFunc messageGotten)
        {
            client = connection;
            writer = new StreamWriter(client.GetStream());
            reader = new StreamReader(client.GetStream());

            try
            {
                //This will block other people from joining. Fix.
                ipAddress = reader.ReadLine();
                name = reader.ReadLine();
                if (name == null)
                { name = "Unnamed user"; }
            }
            catch
            { name = "Unnamed user"; }
            textBoxWriter = messageGotten;

            receiveMessage = new Thread(new ThreadStart(getMessage));
            receiveMessage.IsBackground = true;
            receiveMessage.Start();
        }
示例#30
0
        private void SendBytes(IPEndPoint endpoint, byte[] buffer)
        {
            using (var client = new System.Net.Sockets.TcpClient())
            {
                client.Connect(endpoint);

                var stream = client.GetStream();
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();

                client.Close();
            }
        }
示例#31
0
        public string Connect()
        {
            CQ = new CommandQueue();
            if (this.online)
            {
                // Networking shit
                try
                {
                    TC = new System.Net.Sockets.TcpClient();
                    //TC.Connect("169.254.19.75", 3000);
                    IAsyncResult result = TC.BeginConnect("169.254.67.42", 3000, null, null);

                    if (!result.AsyncWaitHandle.WaitOne(8000, true)) // 4 sec timout
                    {
                        TC.Close();
                        throw new Exception();
                    }

                    SW = new StreamWriter(TC.GetStream());
                    //request dwarf count from server
                    //SW.WriteLine("add dwarf");
                    //SW.Flush();
                    StreamReader SR = new StreamReader(TC.GetStream());
                    string name = SR.ReadLine();
                    t = new Thread(new ParameterizedThreadStart(runListener));
                    t.Start(CQ);
                    return name;
                }
                catch (Exception e)
                {
                    this.online = false;
                }
                return "error";
            }
            else
            {
                return "0";
            }
        }
示例#32
0
 static void Main(string[] args)
 {
     try
     {
         serverSocket = new System.Net.Sockets.TcpClient("suchlol.com", 6969);
         if (serverSocket.Connected)
         {
             System.Console.WriteLine("Receiving info from Kafka.");
         }
         stream = serverSocket.GetStream();
         if (stream.CanRead)
         {
             System.Console.WriteLine("Stream is working.");
         }
         // Send the message to the connected TcpServer.
         //in1 = new BufferedStream(new InputStreamReader(serverSocket.getInputStream()));
     }
     catch (Exception e)
     {
         System.Console.WriteLine(e);
     }
     //perform the update portion.
     //while true! oh no!  couldn't find a Console utility that would do it while the Console it open.
     while (true)
     {
         try
         {
             Byte[] data;
             data = new Byte[256];
             // String to store the response ASCII representation.
             String responseData = String.Empty;
             // Read the first batch of the TcpServer response bytes.
             Int32 bytes = stream.Read(data, 0, data.Length);
             responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
             Console.WriteLine("Received: {0}", responseData);
         }
         catch (IOException e)
         {
             System.Console.WriteLine(e.Message);
         }
     }
     //perform the update portion.
     try
     {
         serverSocket.Close();
     }
     catch (IOException e)
     {
         Console.WriteLine(e.StackTrace);
     }
 }
示例#33
0
        public static void PrintHubLabel(string hub_serial, string zplfile, string printer_addres)
        {
            string hub_mac;
            string hub_id;

            using (CLStoreEntities cx = new CLStoreEntities())
            {
                var lhs = cx.LowesHubs.Where(lh => lh.smt_serial == hub_serial).OrderByDescending(lh => lh.date).First();
                hub_mac = lhs.MacAddress.MAC.ToString("X12");
                hub_id  = lhs.hub_id;
            }

            // get the zpl file
            System.IO.FileStream fs_zpl = new System.IO.FileStream(zplfile, System.IO.FileMode.Open);
            byte[] zpl_file_bytes       = new byte[fs_zpl.Length];
            fs_zpl.Read(zpl_file_bytes, 0, zpl_file_bytes.Length);

            // Open connection
            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            int port = 9100;

            client.Connect(printer_addres, port);

            // Write ZPL String to connection
            System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());

            string short_serial = hub_serial;

            if (short_serial.StartsWith("CLT"))
            {
                short_serial = short_serial.Substring(3);
            }
            string barcode_serial =
                ">;" +
                short_serial.Substring(0, short_serial.Length - 1) +
                ">6" +
                short_serial[short_serial.Length - 1];

            object[] data = new object[4] {
                short_serial, barcode_serial, hub_mac, hub_id
            };

            string label = string.Format(System.Text.Encoding.UTF8.GetString(zpl_file_bytes), data);

            writer.Write(label);
            writer.Flush();

            // Close Connection
            writer.Close();
            client.Close();
        }
示例#34
0
        /// <summary>
        /// Download image
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        private static async Task DownloadImageAsync(string imagePath)
        {
            using var tcp = new System.Net.Sockets.TcpClient(Host, Port);
            Stream networkStream = tcp.GetStream();

            tcp.SendTimeout    = 500;
            tcp.ReceiveTimeout = 1000;
            // Send request headers
            var builder = new StringBuilder();

            builder.AppendLine(GetHeaders(imagePath));
            builder.AppendLine();
            var header = Encoding.ASCII.GetBytes(builder.ToString());

            if (Port == 443)
            {
                var sslStream = new SslStream(networkStream, false, ValidateServerCertificate, null);
                await sslStream.AuthenticateAsClientAsync("127.0.0.1");

                networkStream = sslStream;
            }

            await networkStream.WriteAsync(header, 0, header.Length);

            // receive data
            var memory = new MemoryStream();


            await networkStream.CopyToAsync(memory);

            memory.Position = 0;
            var data    = memory.ToArray();
            var index   = BinaryMatch(data, Encoding.ASCII.GetBytes("\r\n\r\n")) + 4;
            var imgName = imagePath.Split("/").LastOrDefault();
            var dir     = Path.Combine(AppContext.BaseDirectory, "images");

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var filePath = Path.Combine(dir, $"{imgName}");

            await using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(data, index, data.Length - index);
            }

            memory.Position = index;
            memory.Close();
            networkStream.Close();
        }
示例#35
0
        public override void Send(Envelope envelope)
        {
            var messageId = envelope?.Contents?.MessageID ?? null;

            byte[] messageBytes  = envelope.Contents.Encode();
            byte[] messageLength = BitConverter.GetBytes(messageBytes.Length);

            byte[] bytesToSend = new byte[messageLength.Length + messageBytes.Length];

            Buffer.BlockCopy(messageLength, 0, bytesToSend, 0, messageLength.Length);
            Buffer.BlockCopy(messageBytes, 0, bytesToSend, messageLength.Length, messageBytes.Length);

            try
            {
                if (!myTcpClient.Connected)
                {
                    //The following COULD cause us to connect to the wrong client, but in our case, by the time
                    //this method gets called, we have already vetted the envelope "To" to this correct TcpClient
                    Connect(envelope.To);
                }

                if (myTcpClient.Connected)
                {
                    System.Net.Sockets.NetworkStream stream = myTcpClient.GetStream();
                    stream.Write(bytesToSend, 0, bytesToSend.Length);
                    ///stream.Close();
                }
                else
                {
                    Log.Error("TCP Message not sent, no connected was made.");
                }
            }
            catch (Exception e)
            {
                Log.Error($"error sending message to {envelope.To}");
                Log.Error(e.Message);
            }
        }
示例#36
0
 private ErrCode SendTCP(CtrlCmd param, MemoryStream send, ref MemoryStream res)
 {
     lock (thisLock)
     {
         // 接続
         using (var tcp = new System.Net.Sockets.TcpClient())
         {
             try
             {
                 tcp.Connect(ip, (int)port);
             }
             catch (System.Net.Sockets.SocketException)
             {
                 return(ErrCode.CMD_ERR_CONNECT);
             }
             using (System.Net.Sockets.NetworkStream ns = tcp.GetStream())
             {
                 // 送信
                 var head = new byte[8];
                 BitConverter.GetBytes((uint)param).CopyTo(head, 0);
                 BitConverter.GetBytes((uint)(send == null ? 0 : send.Length)).CopyTo(head, 4);
                 ns.Write(head, 0, 8);
                 if (send != null && send.Length != 0)
                 {
                     send.Close();
                     byte[] data = send.ToArray();
                     ns.Write(data, 0, data.Length);
                 }
                 // 受信
                 if (ns.Read(head, 0, 8) != 8)
                 {
                     return(ErrCode.CMD_ERR);
                 }
                 uint resParam = BitConverter.ToUInt32(head, 0);
                 var  resData  = new byte[BitConverter.ToUInt32(head, 4)];
                 for (int n = 0; n < resData.Length;)
                 {
                     int m = ns.Read(resData, n, resData.Length - n);
                     if (m <= 0)
                     {
                         return(ErrCode.CMD_ERR);
                     }
                     n += m;
                 }
                 res = new MemoryStream(resData, false);
                 return(Enum.IsDefined(typeof(ErrCode), resParam) ? (ErrCode)resParam : ErrCode.CMD_ERR);
             }
         }
     }
 }
示例#37
0
        public MouseClient(string ip, int port = 7001)
        {
            this.Ip   = ip;
            this.Port = port;

            var client = new System.Net.Sockets.TcpClient(ip, port);

            client.NoDelay = true;
            var clientStream = client.GetStream();
            var clientWriter = new System.IO.BinaryWriter(clientStream);

            this.TcpClient    = client;
            this.ClientWriter = clientWriter;
        }
示例#38
0
        public bool DataTravelTO(System.Net.Sockets.TcpClient tcpClient, string rawDataToSend)
        {
            try
            {
                byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes(rawDataToSend);
                tcpClient.GetStream().Write(dataToSend, 0, dataToSend.Length); // Send data

                return(true);                                                  // if we got here then it worked!

        #if DEBUG
            } catch (Exception exc)
            { Console.WriteLine(exc.Message); CloseTCPStream(tcpClient); RestartApplication(1); return(false); }
        #else
            } catch (Exception)
示例#39
0
        /// <summary> Build a DProtocol object from a the given socket connection.</summary>
        internal static DProtocol createFromSocket(System.Net.Sockets.TcpClient s)
        {
            // For performance reasons, it is very important that we setTcpNoDelay(true),
            // thus disabling Nagle's algorithm.  Google for TCP_NODELAY or Nagle
            // for more information.
            //
            // In addition, we now use a BufferedOutputStream instead of an OutputStream.
            //
            // These changes result in a huge speedup on the Mac.

            s.NoDelay = true;

            // We need to make sure that the socket is in blocking mode or BufferedStream
            // gets confused and screws up.
            s.ReceiveTimeout = 0;

            BufferedStream inStream  = new BufferedStream(s.GetStream());
            BufferedStream outStream = new BufferedStream(s.GetStream());

            DProtocol dp = new DProtocol(inStream, outStream);

            return(dp);
        }
 private void  Verify(sbyte message)
 {
     try
     {
         System.Net.Sockets.TcpClient s           = new System.Net.Sockets.TcpClient(Enclosing_Instance.host, Enclosing_Instance.port);
         System.IO.Stream             out_Renamed = s.GetStream();
         out_Renamed.WriteByte((byte)Enclosing_Instance.id);
         out_Renamed.WriteByte((byte)message);
         System.IO.Stream in_Renamed = s.GetStream();
         int result = in_Renamed.ReadByte();
         in_Renamed.Close();
         out_Renamed.Close();
         s.Close();
         if (result != 0)
         {
             throw new System.SystemException("lock was double acquired");
         }
     }
     catch (System.Exception e)
     {
         throw new System.SystemException(e.Message, e);
     }
 }
示例#41
0
        private static void SendCommand(string command)
        {
#if local
            if (client != null)
            {
                if (writer == null)
                {
                    writer = new System.IO.StreamWriter(client.GetStream(), System.Text.Encoding.ASCII);
                }
                writer.WriteLine(command);
                writer.Flush();
            }
            System.Console.WriteLine(command);
#endif
        }
示例#42
0
 private void Form1_Load(object sender, System.EventArgs e)
 {
     label1.Text = "";
     Listener    = new System.Net.Sockets.TcpListener(2020);              //Inicializo el TCPListener en el puerto 2020
     this.Text   = "Sensai.Net ChatServer... >;)";
     Listener.Start();                                                    //Pongo el puerto en Escucha
     Cliente = Listener.AcceptTcpClient();                                //Acepto la conexion
     Stream  = Cliente.GetStream();                                       //Obtengo el flujo de Datos
     byte [] buff = new byte[256];                                        //Declaro arreglo de bytes para almacenar lo recibido
     buff = System.Text.Encoding.ASCII.GetBytes("Hola ya te conectaste"); //Convierto la cadena de Saludo a Bytes
     if (Stream.CanWrite)                                                 //Si puedo escribir Escribo
     {
         Stream.Write(buff, 0, buff.Length);
     }
 }
示例#43
0
 public bool SendMessage(System.Net.Sockets.TcpClient client, string message)
 {
     try
     {
         var streamWriter = new StreamWriter(client.GetStream());
         streamWriter.WriteLine(message);
         streamWriter.Flush();
         return(true);
     }
     catch (Exception ex)
     {
         //TODO: Implement log mechanism
         return(false);
     }
 }
示例#44
0
        public Communicator(System.Net.Sockets.TcpClient connection, WriteMessageFunc messageGotten)
        {
            client = connection;
            writer = new StreamWriter(client.GetStream());
            reader = new StreamReader(client.GetStream());

            try
            {
                //This will block other people from joining. Fix.
                ipAddress = reader.ReadLine();
                name      = reader.ReadLine();
                if (name == null)
                {
                    name = "Unnamed user";
                }
            }
            catch
            { name = "Unnamed user"; }
            textBoxWriter = messageGotten;

            receiveMessage = new Thread(new ThreadStart(getMessage));
            receiveMessage.IsBackground = true;
            receiveMessage.Start();
        }
示例#45
0
        public static void acceptclient(object e)
        {
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
            System.Threading.ThreadPool.QueueUserWorkItem(acceptclient);

            System.Net.Sockets.NetworkStream ns = client.GetStream();
            Console.WriteLine("connect");

            byte[] readBytes = new byte[4];

            int resSize = ns.Read(readBytes, 0, readBytes.Length);
            int i       = BitConverter.ToInt32(readBytes, 0);

            Console.WriteLine(readBytes + " --> " + i);
        }
示例#46
0
        public FormAdministrator(System.Net.Sockets.TcpClient client)
        {
            InitializeComponent();

            try
            {
                _client = client;
                _stream = client.GetStream();
                LoadSubsidiaryInCombobox();
            }
            catch (Exception)
            {
                Close();
            }
        }
示例#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 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
        protected internal async void SendFile(string RemoteSeverName, int intFileSendPort, string sFullPathToFile) //Send file to _textBoxClientIpText():_numericUpDownClien()
        {
            client = new System.Net.Sockets.TcpClient(RemoteSeverName, intFileSendPort);
            try
            {
                using (System.IO.FileStream inputStream = System.IO.File.OpenRead(sFullPathToFile))
                {
                    using (System.Net.Sockets.NetworkStream outputStream = client.GetStream())
                    {
                        using (var cancellationTokenSource = new System.Threading.CancellationTokenSource(5000))
                        {
                            using (cancellationTokenSource.Token.Register(() => outputStream.Close()))
                            {
                                using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(outputStream))
                                {
                                    long   lenght     = inputStream.Length;
                                    long   totalBytes = 0;
                                    int    readBytes  = 0;
                                    byte[] buffer     = new byte[1024];
                                    try
                                    {
                                        writer.Write(System.IO.Path.GetFileName(sFullPathToFile));
                                        writer.Write(lenght);
                                        do
                                        {
                                            readBytes = await inputStream.ReadAsync(buffer, 0, buffer.Length);

                                            await outputStream.WriteAsync(buffer, 0, readBytes, cancellationTokenSource.Token);

                                            totalBytes += readBytes;
                                        } while (client.Connected && totalBytes < lenght);
                                    }
                                    catch (TimeoutException e)
                                    {
                                        readBytes = -1;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception expt)
            {
                Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Can't send file to " + RemoteSeverName + ": " + expt.Message);
            }
            client.Close();
        }
 /// <summary>
 /// Saving a mail message before beeing sent by the SMTP client
 /// </summary>
 /// <param name="self">The caller</param>
 /// <param name="imapServer">The address of the IMAP server</param>
 /// <param name="imapPort">The port of the IMAP server</param>
 /// <param name="userName">The username to log on to the IMAP server</param>
 /// <param name="password">The password to log on to the IMAP server</param>
 /// <param name="sentFolderName">The name of the folder where the message will be saved</param>
 /// <param name="mailMessage">The message being saved</param>
 public static void SendAndSaveMessageToIMAP(this System.Net.Mail.SmtpClient self, System.Net.Mail.MailMessage mailMessage, string imapServer, int imapPort, string userName, string password, string sentFolderName)
 {
     try
     {
         path = System.Environment.CurrentDirectory + "\\emailresponse.txt";
         if (System.IO.File.Exists(path))
         {
             System.IO.File.Delete(path);
         }
         sw   = new System.IO.StreamWriter(System.IO.File.Create(path));
         tcpc = new System.Net.Sockets.TcpClient(imapServer, imapPort);
         ssl  = new System.Net.Security.SslStream(tcpc.GetStream());
         ssl.AuthenticateAsClient(imapServer);
         SendCommandAndReceiveResponse("");
         SendCommandAndReceiveResponse(string.Format("$ LOGIN {1} {2}  {0}", System.Environment.NewLine, userName, password));
         using (var m = mailMessage.RawMessage())
         {
             m.Position = 0;
             var sr    = new System.IO.StreamReader(m);
             var myStr = sr.ReadToEnd();
             SendCommandAndReceiveResponse(string.Format("$ APPEND {1} (\\Seen) {{{2}}}{0}", System.Environment.NewLine, sentFolderName, myStr.Length));
             SendCommandAndReceiveResponse(string.Format("{1}{0}", System.Environment.NewLine, myStr));
         }
         SendCommandAndReceiveResponse(string.Format("$ LOGOUT{0}", System.Environment.NewLine));
     }
     catch (System.Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("error: " + ex.Message);
     }
     finally
     {
         if (sw != null)
         {
             sw.Close();
             sw.Dispose();
         }
         if (ssl != null)
         {
             ssl.Close();
             ssl.Dispose();
         }
         if (tcpc != null)
         {
             tcpc.Close();
         }
     }
     self.Send(mailMessage);
 }
        /// <summary>
        /// 在web访问到来时取得访问报告,并返回给用户
        /// </summary>
        /// <param name="a"></param>
        void Web_AfterConnectionGetReportAndSendToUser(object a)
        {
            System.Net.Sockets.TcpClient socketcomein = a as System.Net.Sockets.TcpClient;

            if (socketcomein == null)
            {
                LogInToEvent.WriteError("未知错误:socketcomein == null");
                return;
            }
            try
            {
                var stream = socketcomein.GetStream();
                System.IO.StreamReader rstream = new System.IO.StreamReader(stream);
                string i = rstream.ReadLine();
                var where = i.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (!
                    (where.Length == 3 &&
                     where[1].Trim().StartsWith("/"))
                    )
                {
                    string errorMessage = "请求格式错误,请发送 GET / HTTP1.1 \n" + i;
                    foreach (var p in where)
                    {
                        errorMessage += "\n" + p + "\n";
                    }
                    var error_gs = System.Text.Encoding.UTF8.GetBytes(errorMessage);
                    stream.Write(error_gs, 0, error_gs.Length);
                    stream.Close();
                    socketcomein.Close();
                    return;
                }
                string report = Web_GetReport(where[1]);
                string head   = "http/1.1 200 ok\n" +
                                "Content-Type: text/html\n";
                byte[] content = System.Text.Encoding.UTF8.GetBytes(report);
                head += "Content-Length:" + content.Length + "\n\n";
                var headstr = System.Text.Encoding.UTF8.GetBytes(head);
                stream.Write(headstr, 0, headstr.Length);
                stream.Write(content, 0, content.Length);
                stream.Close();
                socketcomein.Close();
            }
            catch (Exception e)
            {
                LogInToEvent.WriteError(e.ToString());
                return;
            }
        }
        // Get NetworkStream Object from TCPClient
        protected bool getStream(ref System.Net.Sockets.NetworkStream ns)
        {
            bool error = false;

            try {
                ns = client.GetStream();
            } catch (System.Exception e) {
                error            = true;
                lastErrorMessage = "Connection is not propertly established";
                if (log.IsErrorEnabled)
                {
                    log.Error(lastErrorMessage, e);
                }
            }
            return(!error);
        }
示例#52
0
        static void Main(string[] args)
        {
            var ip   = System.Net.IPAddress.Parse("127.0.0.1");
            var port = 50001;

            Console.WriteLine("请输入要发送的消息");
            while (true)
            {
                var msg    = Console.ReadLine();
                var client = new System.Net.Sockets.TcpClient(System.Net.Sockets.AddressFamily.InterNetwork);
                client.Connect(ip, port);
                using (var writer = new System.IO.StreamWriter(client.GetStream())) {
                    writer.Write(msg);
                }
            }
        }
示例#53
0
 private void Init(string address, int port, System.Net.Sockets.TcpClient connection)
 {
     this.IsDisposed = false;
     this.Address    = address;
     this.Port       = port;
     this.Stream     = connection.GetStream();
     this.Stream.WriteByte(0xFF);
     this.Stream.WriteByte(0xFB);
     this.Stream.WriteByte(0x01);
     this.Stream.ReadAsync(this.InputBuffer, 0, this.InputBuffer.Length);
     this.Stream.WriteByte((byte)'>');
     this.InputObservable = System.Reactive.Linq.Observable.ToObservable <byte>(this.Read());
     Session.Connections.Add(this);
     App.Log($"+++ {this.Address} ({this.Port})");
     this.InputObservableSubscription = this.InputObservable.Subscribe(this.Read);
 }
示例#54
0
        private void button1_Click(object sender, EventArgs e)
        {
            NetworkStream serverStream = clientSocket.GetStream();

            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);

            msg(returndata);
            textBox2.Text = "";
            textBox2.Focus();
        }
示例#55
0
 public TcpClient(string ipAddr, int port)
 {
     Client = new System.Net.Sockets.TcpClient();
     CConsole.DarkGray("[TcpClient] Connecting");
     Client.ConnectAsync(ipAddr, port).Wait();
     if (!Client.Connected)
     {
         CConsole.Red("!!! Error Connecting TcpClient to port {0} !!!", port);
         throw new Exception("notConnected");
     }
     else
     {
         CConsole.DarkGray("[TcpClient] Connected");
         Stream = Client.GetStream();
     }
 }
        private void DoWork(object state)
        {
            System.Net.Sockets.TcpClient socket = state as System.Net.Sockets.TcpClient;

            while (!this.done)
            {
                goSignal.WaitOne();
                object o = DequeueObject();
                if (o == null)
                {
                    continue;
                }

                formatter.Serialize(socket.GetStream(), o);
            }
        }
示例#57
0
        public bool TryGet​Request​Stream()
        {
            if (SmtpStream == null)
            {
                Tcp = new System.Net.Sockets.TcpClient();
                Tcp.Connect(Hostname, Port);

                var stream = new SslStream(Tcp.GetStream())
                {
                    ReadTimeout = 30000
                };
                stream.AuthenticateAsClient(Hostname);
                SmtpStream = stream;
            }
            return(SmtpStream != null);
        }
示例#58
0
        public void listen()
        {
            //System.Net.IPAddress ip = System.Net.IPAddress.Parse(IP_add);
            listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port);
            System.Console.WriteLine("Port:{0}", port);

            listener.Start();

            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
            System.Console.WriteLine("connect");

            ns              = client.GetStream();
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;
            System.Console.WriteLine("connect2");
        }
示例#59
0
 private ErrCode SendTCP(CtrlCmd param, MemoryStream send, ref MemoryStream res)
 {
     {
         if (ip == null)
         {
             return(ErrCode.CMD_ERR_CONNECT);
         }
         // 接続
         using (var tcp = new System.Net.Sockets.TcpClient(ip.AddressFamily))
         {
             try
             {
                 tcp.Connect(ip, (int)port);
             }
             catch (System.Net.Sockets.SocketException)
             {
                 return(ErrCode.CMD_ERR_CONNECT);
             }
             using (System.Net.Sockets.NetworkStream ns = tcp.GetStream())
             {
                 // 送信
                 var head = new byte[8 + (send == null ? 0 : send.Length)];
                 BitConverter.GetBytes((uint)param).CopyTo(head, 0);
                 BitConverter.GetBytes((uint)(send == null ? 0 : send.Length)).CopyTo(head, 4);
                 if (send != null && send.Length != 0)
                 {
                     send.Close();
                     send.ToArray().CopyTo(head, 8);
                 }
                 ns.Write(head, 0, head.Length);
                 // 受信
                 if (ReadAll(ns, head, 0, 8) != 8)
                 {
                     return(ErrCode.CMD_ERR_DISCONNECT);
                 }
                 uint resParam = BitConverter.ToUInt32(head, 0);
                 var  resData  = new byte[BitConverter.ToUInt32(head, 4)];
                 if (ReadAll(ns, resData, 0, resData.Length) != resData.Length)
                 {
                     return(ErrCode.CMD_ERR_DISCONNECT);
                 }
                 res = new MemoryStream(resData, false);
                 return(Enum.IsDefined(typeof(ErrCode), resParam) ? (ErrCode)resParam : ErrCode.CMD_ERR);
             }
         }
     }
 }
示例#60
0
        private static async Task MainLoop(string[] args, CancellationTokenSource tokenSource, int port)
        {
            System.Net.Sockets.TcpClient   socket   = null;
            System.Net.Sockets.TcpListener listener = null;

            listener = new System.Net.Sockets.TcpListener(IPAddress.Any, port);
            listener.Start();

            // *** starting to listen to socket

            while (!tokenSource.Token.WaitHandle.WaitOne(1))
            {
                Console.WriteLine("listening on port " + port);
                try
                {
                    socket = await listener.AcceptTcpClientAsync();

                    Console.WriteLine("Connected!");

                    var ai = new Ai();

                    using (var stream = socket.GetStream())
                        using (var sr = new StreamReader(stream))
                            using (var sw = new StreamWriter(stream))
                            {
                                while (!tokenSource.Token.WaitHandle.WaitOne(1))
                                {
                                    string line = await sr.ReadLineAsync();

                                    Console.WriteLine("received " + line);

                                    var commands = ai.GoJson(line);

                                    await sw.WriteAsync(commands);

                                    await sw.FlushAsync();
                                }
                            }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("\n" + e.Message);
                    socket?.Dispose();
                }
            }
            socket?.Dispose();
        }