Read() public method

public Read ( byte buffer, int offset, int size ) : int
buffer byte
offset int
size int
return int
Beispiel #1
0
        /// <summary>
        /// 初始化实例并开启侦测
        /// </summary>
        /// <param name="inputClient"></param>
        /// <param name="replay"></param>
        public GameData(ref TcpClient inputClient, Action<string, byte[]> replay)
        {
            client = inputClient;
            stream = inputClient.GetStream();
            ReplyNewMessage = new Action<string, byte[]>(replay);
            stopReadFlag = false;

            Task.Run(() =>
            {

                while (true) {
                    if (stopReadFlag == true) { break; }

                    //读取数据长度
                    byte[] buffer = new byte[4];
                    stream.Read(buffer, 0, 4);

                    int length = BitConverter.ToInt32(buffer, 0);

                    //读取正文
                    buffer = new byte[length];
                    stream.Read(buffer, 0, length);

                    string head;
                    byte[] contant;

                    BallanceOnline.CombineAndSplitSign.Split(buffer, out head, out contant);

                    //调用委托处理
                    ReplyNewMessage(head, contant);
                }

            });
        }
Beispiel #2
0
        public ServerMessage(NetworkStream clientStream, byte[] buffer, ref int bytesRead)
        {
            //blocks until a client sends a message
            bytesRead = clientStream.Read(buffer, 0, ServerMessage.headerSize);
            if (bytesRead < ServerMessage.headerSize)
            {
                bytesRead = 0;
                return;
            }

            IntPtr ptr = Marshal.AllocHGlobal(bytesRead);
            Marshal.Copy(buffer, 0, ptr, ServerMessage.headerSize);
            header = (MessageHeader)Marshal.PtrToStructure(ptr, header.GetType());
            Marshal.FreeHGlobal(ptr);

            //Utils.Log("Client " + client.account.email + " got a packet with opcode "+msg.header.opcode, 2);

            if (header.size > 0)
            {
                byte[] databuffer = null;
                databuffer = new byte[header.size + 1];
                bytesRead = clientStream.Read(databuffer, 0, header.size);
                if (bytesRead < header.size)
                {
                    bytesRead = 0;
                }

                size = buffer.Length;
                target = new MemoryStream(buffer, 0, buffer.Length, false, true);
                reader = new BinaryReader(target, Encoding.ASCII);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Blocking call to read a full Message object from a given stream
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static Message ReadMessage(NetworkStream stream)
        {
            Debug.Assert(stream.CanRead);

            byte[] messageBytes = new byte[Message.MaxSize];
            byte[] sizeBytes = new byte[4];
            int bytesRead = 0;

            // Read the initial size from the stream
            while (bytesRead < 4)
            {
                bytesRead += stream.Read(sizeBytes, bytesRead, sizeBytes.Length);
            }

            int messageSize = BitConverter.ToInt32(sizeBytes, 0);
            Debug.Assert(messageSize < Message.MaxSize);
            bytesRead = 0;

            // Get the message bytes
            while (bytesRead < messageSize)
            {
                bytesRead += stream.Read(messageBytes, bytesRead, messageBytes.Length - bytesRead);
            }

            // Deserialize the message
            return Message.Deserialize(messageBytes);
        }
Beispiel #4
0
        static void getFile(NetworkStream ns)
        {
            UInt64 fLen;
            int readBytes = 0;
            byte[] message = new byte[8];
            FileStream fs;

            try
            {
                fs = new FileStream("Config.xml", FileMode.Create, FileAccess.Write);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            readBytes = ns.Read(message, 0, 8);
            fLen = BitConverter.ToUInt64(message,0);
            message = new byte[4096];

            do
            {
                readBytes = ns.Read(message, 0, 4096);
                fs.Write(message, 0, readBytes);
                fLen -= Convert.ToUInt64(readBytes);
            } while (fLen > 0);
            fs.Close();
        }
        public static bool Connect(string ip, int port, string pass)
        {
            Console.WriteLine("Attempting to connect to RCON for announcements.");

            try
            {
                tcp = new TcpClient();
                tcp.Connect(ip, port);
                stream = tcp.GetStream();
                byte[] array = new byte[1024];
                int count = stream.Read(array, 0, array.Length);
                string @string = Encoding.ASCII.GetString(array, 0, count);
                if (@string.Substring(0, 4) != "v001")
                {
                    Failed(string.Concat(new string[]
                    {
                        "Server is running a newer protocol (",
                        @string.Substring(0, 4),
                        ").",
                        Environment.NewLine,
                        "You need to download a new version of RxCommand."
                    }));
                }
                else
                {
                    gameVersion = @string.Substring(4);
                    gameVersion.Trim();
                    WriteLine('a' + pass);
                    count = stream.Read(array, 0, array.Length);
                    @string = Encoding.ASCII.GetString(array, 0, count);
                    if (@string.Substring(0, 1) != "a")
                    {
                        Failed(@string.Substring(1));
                    }
                    else
                    {
                        receiver = new Thread(new ThreadStart(ReceiveLoop));
                        receiver.Start();
                        while (!receiver.IsAlive)
                        {

                        }

                        Console.WriteLine("Successfully connected to RCON.");

                        return true;
                    }
                }
            }
            catch (SocketException)
            {
                Failed("Could not connect to server.");
                tcp = null;
            }

            return false;
        }
 public static string ReadStreamIntoString(NetworkStream ns)
 {
     byte[] buffer = new byte[1024];
     ns.Read(buffer, 0, buffer.Length);
     while (ns.DataAvailable)
     {
         ns.Read(buffer, 0, buffer.Length);
     }
     ASCIIEncoding enc = new ASCIIEncoding();
     return enc.GetString(buffer);
 }
Beispiel #7
0
        /// <summary>
        /// Receieves a single object over the specified stream
        /// </summary>
        /// <param name="stream">Stream to receive the message from</param>
        /// <returns>Object received</returns>
        public static object Recieve(NetworkStream stream)
        {
            int dataLength;
            byte[] data = new byte[sizeof(Int32)];

            int bytesRead = 0;
            int totalBytesRead = 0;

            try {
                // Read the length integer
                do {
                    bytesRead = stream.Read(data, totalBytesRead, (data.Length - totalBytesRead));
                    totalBytesRead += bytesRead;
                } while (totalBytesRead < sizeof(Int32) && bytesRead != 0);

                if (totalBytesRead < sizeof(Int32)) {
                    if (totalBytesRead != 0) Console.Error.WriteLine("Message Recieve Failed: connection closed unexpectedly");
                    return null;
                }

                if (BitConverter.IsLittleEndian) Array.Reverse(data);
                dataLength = BitConverter.ToInt32(data, 0);

                if (dataLength == 0) {
                    // A test message was sent.
                    return "Test";
                } else {
                    data = new byte[dataLength];

                    // Read data until the client disconnects
                    totalBytesRead = 0;
                    do {
                        bytesRead = stream.Read(data, totalBytesRead, (dataLength - totalBytesRead));
                        totalBytesRead += bytesRead;
                    } while (totalBytesRead < dataLength && bytesRead != 0);

                    if (totalBytesRead < dataLength) {
                        Console.Error.WriteLine("Message Receive Failed: connection closed unexpectedly");
                        return null;
                    }

                    return Unpack(data);
                }
            } catch (Exception e) {
                Console.Error.WriteLine("A socket error has occured: " + e.ToString());
                return null;
            }
        }
Beispiel #8
0
        private void getMessage()

        {

            while (true)

            {

                serverStream = clientSocket.GetStream();

                int buffSize = 0;

                byte[] inStream = new byte[10025];

                buffSize = clientSocket.ReceiveBufferSize;

                serverStream.Read(inStream, 0, buffSize);

                string returndata = System.Text.Encoding.ASCII.GetString(inStream);

                readData = "" + returndata;

                msg();

            }

        }
Beispiel #9
0
        //I needed a blocking read for the video because I realized it was causing major issues if the
        //Video was not fully recived into our buffer when this function was called.
        //Read would return without reading the whole file
        //This function will not return until it reads the specified number of bytes
        //Or a timeout with a default of 1 second is reached without reading anything
        public static byte[] ReadBytesBlocking(NetworkStream networkStream, int length = 256, int TimeoutMS = 1000)
        {
            byte[] bytes = new byte[length];
            int numBytesRead = 0;
            int lastBytesRead;
            System.Diagnostics.Stopwatch t = System.Diagnostics.Stopwatch.StartNew();

            while (numBytesRead < length)
            {
                int i = networkStream.Read(bytes, numBytesRead, length - numBytesRead);
                lastBytesRead = numBytesRead;
                numBytesRead += i;
                if (lastBytesRead != numBytesRead) // if data was recieved
                {
                    t.Restart();// reset timeout
                }
                else
                {
                    System.Threading.Thread.Sleep(100); // wait for data.
                }
                if(t.ElapsedMilliseconds > TimeoutMS)
                {
                    byte[] Error = new byte[1];
                    Error[0] = 0;
                    return Error;
                }
            }
            return bytes;
        }
Beispiel #10
0
        /// <summary>
        /// Accepts message from client.
        /// </summary>
        /// <param name="networkStream"></param>
        /// <returns></returns>
        public static string Read(NetworkStream networkStream, int length = 256)
        {
            byte[] bytes = new byte[length];
            int i = networkStream.Read(bytes, 0, length);
            return Encoding.ASCII.GetString(bytes, 0, i);

            //var header = new byte[4];
            //var bytesLeft = 4;
            //var offset = 0;

            //// get length of content
            //while (bytesLeft > 0)
            //{
            //    var bytesRead = networkStream.Read(header, offset, bytesLeft);
            //    offset += bytesRead;
            //    bytesLeft -= bytesRead;
            //}

            //bytesLeft = BitConverter.ToInt32(header, 0); // length of content
            //offset = 0;

            //byte[] contentBytes = new byte[bytesLeft];

            //// get the actual content
            //while (bytesLeft > 0)
            //{
            //    var bytesRead = networkStream.Read(contentBytes, offset, bytesLeft);
            //    offset += bytesRead;
            //    bytesLeft -= bytesRead;
            //}

            //return Encoding.ASCII.GetString(contentBytes); // return the content
        }
 private void ServerConnection(NetworkStream stream)
 {
     int RecievedSymbols = 0;
     byte[] recieved = new byte[2048];
     byte[] to_send = new byte[2048];
     string task = "";
     while ( (RecievedSymbols = stream.Read(recieved, 0, recieved.Length)) > 0 )
     {
         task = Resize(recieved);
         task = TaskToDo(task);
         Console.WriteLine(task);
         if (task.Equals("closed -1"))
         {
             to_send = Encoding.ASCII.GetBytes(task);
             stream.Write(to_send, 0, to_send.Length);
             client.Close();
             return;
         }
         else
         {
             to_send = Encoding.ASCII.GetBytes(task);
             stream.Write(to_send, 0, to_send.Length);
         }
        Array.Clear(to_send, 0, to_send.Length);
        Array.Clear(recieved, 0, recieved.Length);
     }
 }
Beispiel #12
0
        protected void dataRecv(NetworkStream ns)
        {
            byte[] lengthByte = new byte[4];

            ns.Read (lengthByte, 0, lengthByte.Length);
            Length = BitConverter.ToUInt32 (lengthByte, 0);

            data = new byte[Length];
            Array.Copy (lengthByte, data, lengthByte.Length);

            // 全データ受信する
            ns.Read (data, 4, (int)(Length - 4));

            // PacketType
            PacketType = (PacketType)BitConverter.ToInt32(data, 4);
        }
Beispiel #13
0
        /// <summary>
        /// 获取通信返回信息
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static void Work(string cmd, NetworkStream stream)
        {
            Byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(cmd);
            stream.Write(buffer, 0, buffer.Length);

            Console.WriteLine("发送信息:" +cmd);

            buffer = new Byte[1024];
            StringBuilder sb = new StringBuilder();
            Int32 numberOfBytesRead = 0;
            do
            {
                numberOfBytesRead = stream.Read(buffer, 0, buffer.Length);
                sb.Append(System.Text.Encoding.GetEncoding("GB2312").GetString(buffer, 0, numberOfBytesRead));
            }
            while (stream.DataAvailable);

            string result = sb.ToString();
            if (string.IsNullOrEmpty(result))
             Console.WriteLine("DServer无响应,请检查服务是否正常运行.");

            if (result.StartsWith("OK"))
            {
                if (result.Length == 2)
                {
                    Console.WriteLine("任务已接收");
                }
                else
                {
                    Console.WriteLine(result.Substring(3));
                }

            }
        }
        public override void Respond(TcpClient client, NetworkStream stream, byte[] message)
        {
            string msgIncoming = Encoding.ASCII.GetString(message, 0, message.Length);
            System.Diagnostics.Debug.WriteLine("RECEIVED//" + msgIncoming + "//");

            switch (msgIncoming)
            {
                case REQ_SEND_CLASS_LIST:

                    List<Class> classList = _helper.GetClasses();
                    SendData(classList, stream);
                    break;

                case REQ_SEND_STUD_LIST:
                    System.Diagnostics.Debug.WriteLine("Requesting class ID");
                    string msgToSend = CMD_SEND_CLASS_ID;
                    byte[] bytesToSend = Encoding.ASCII.GetBytes(msgToSend);
                    stream.Write(bytesToSend, 0, bytesToSend.Length);

                    message = new byte[5];
                    stream.Read(message, 0, message.Length);
                    msgIncoming = Encoding.ASCII.GetString(message, 0, message.Length).Trim();
                    System.Diagnostics.Debug.WriteLine("RECEIVED//" + msgIncoming + "//");
                    List<Student> studentsList = _helper.GetStudentsInClass(new Class(Convert.ToInt32(msgIncoming), ""));
                    SendData(studentsList, stream);
                    break;
            }
        }
Beispiel #15
0
        public string SendAndRecv(string order)
        {
            System.Net.Sockets.NetworkStream ns = this.TCPSocket.GetStream();
            ns.ReadTimeout  = 5000;
            ns.WriteTimeout = 5000;

            byte[] str = MakePacket(order);

            ns.Write(str, 0, str.Length);

            byte[] resBytes = new byte[this.TCPSocket.ReceiveBufferSize];
            int    resSize  = ns.Read(resBytes, 0, resBytes.Length);

            if (resSize <= 5)
            {
                if (resSize <= 0)
                {
                    this.ErrorMessage = "";
                    return("");
                }
                if (resBytes[0] == '-')
                {
                    this.ErrorMessage = R._("メッセージを送信できません。エラーコードが戻りました。\r\n送信データ:\r\n{0}", str.ToString());
                    return("");
                }
                this.ErrorMessage = R._("サーバがおかしな応答を返しました。\r\n送信データ:\r\n{0}\r\n受信データ:\r\n{1}", str.ToString(), U.subrange(resBytes, 0, (uint)resSize).ToString());
                return("");
            }
//            return Encoding.ASCII.GetString(resBytes, 0, resSize);
            return(UnPacket(resBytes, resSize));
        }
Beispiel #16
0
        public String VerSiHayMensajes()
        {
            String Mensaje = "";

            try {
                System.Net.Sockets.NetworkStream stream = TCPCliente.GetStream();

                //Data reciving mechanism
                //Corrigue este metodo para que siempre este en escuchar y cuando llegue un mensaje lo puedas ver inmediatamente.
                if (stream.CanRead)                                                   //Preguntamos si es posible leer
                {
                    if (stream.DataAvailable)                                         //Preguntamos si hay algo por leer
                    {
                        Byte[] data         = new Byte[TCPCliente.ReceiveBufferSize]; //Buffer del tamaño de lo que se recibio
                        string responseData = "";                                     //String to store the response ASCII representation

                        Int32 bytes = stream.Read(data, 0, data.Length);
                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                        //concatenamos los bytes en la variable mensaje para armar el mensaje
                        Mensaje += "Received " + responseData;
                    }
                }
            }
            catch (Exception ex) {
                //ex nunca se usa.. contiene el errorde que no hay mensajes de clientes ya que no se eonctraron clientes.
                //no hay clientes conectados al servidor, asi que no hacemos nada.
            }
            //regresamos el mensaje que se construyo anteriormente
            return(Mensaje);
        }
Beispiel #17
0
        public void RecieveFile(NetworkStream netStream)
        {
            byte[] data = new byte[1024];
            int dataCitit;
            int totalBytes = 0;

            FileStream fs = new FileStream("$temp", FileMode.Create, FileAccess.Write);

            do
            {
                dataCitit = netStream.Read(data, 0, data.Length);
                fs.Write(data, 0, dataCitit);
                totalBytes += dataCitit;

            } while (netStream.DataAvailable);

            fs.Close();
            netStream.Close();

            BinaryFormatter binFormatter = new BinaryFormatter();
            DataTable contentOfFile;
            byte[] outData;

            using (MemoryStream ms = new MemoryStream(File.ReadAllBytes("$temp")))
            {
                contentOfFile = (DataTable) binFormatter.Deserialize(ms);
                outData = (byte[]) contentOfFile.Rows[0].ItemArray.GetValue(2);
            }

            File.WriteAllBytes(contentOfFile.Rows[0].ItemArray.GetValue(0).ToString()+contentOfFile.Rows[0].ItemArray.GetValue(1), outData);
            File.Delete("$temp");
        }
		protected BMSByte ReadBuffer(NetworkStream stream)
		{
			int count = 0;
			while (stream.DataAvailable)
			{
				previousSize = backBuffer.Size;
				backBuffer.SetSize(backBuffer.Size + 1024);

				count += stream.Read(backBuffer.byteArr, previousSize, 1024);
				backBuffer.SetSize(previousSize + count);
			}

			int size = BitConverter.ToInt32(backBuffer.byteArr, 0);

			readBuffer.Clear();

			readBuffer.BlockCopy(backBuffer.byteArr, backBuffer.StartIndex(4), size);

			if (readBuffer.Size + 4 < backBuffer.Size)
				backBuffer.RemoveStart(size + 4);
			else
				backBuffer.Clear();

			return readBuffer;
		}
        public static string ReadHttpHeader(NetworkStream networkStream)
        {
            int length = 1024*16; // 16KB buffer more than enough for http header
            byte[] buffer = new byte[length];
            int offset = 0;
            int bytesRead = 0;
            do
            {
                if (offset >= length)
                {
                    throw new EntityTooLargeException("Http header message too large to fit in buffer (16KB)");
                }

                bytesRead = networkStream.Read(buffer, offset, length - offset);
                offset += bytesRead;
                string header = Encoding.UTF8.GetString(buffer, 0, offset);

                // as per http specification, all headers should end this this
                if (header.Contains("\r\n\r\n"))
                {
                    return header;
                }

            } while (bytesRead > 0);

            return string.Empty;
        }
        public override void ShowUsage()
        {
            //NetWorkStream类是专门用来处理服务器与客户端通信的流。它在网络编程中经常使用,主要是用来处理类似Socket、TcpClient和TcpListener这些类中得到的流。
            //服务器端
            TcpListener lis = new TcpListener(5000);                        //服务器监听
            lis.Start();//启动
            Socket sock = lis.AcceptSocket();                               //阻塞,直到有客户端连接

            NetworkStream netStream = new NetworkStream(sock);              //得到Socket中的流
            if (netStream.DataAvailable)                                    //如果客户端发送了消息
            {
                byte[] data = new byte[1024];                               //定义一个字节数组,用来存放接收的数据
                int len = netStream.Read(data, 0, data.Length);             //从位置开始,读取到字节数组末尾
                string line = Encoding.Default.GetString(data, 0, len);     //把收到的字节转换为字符串
            }

            //客户端
            TcpClient client = new TcpClient();                             //客户端tcp对象
            client.Connect("127.0.0.1", 5000);                              //连接服务器
            NetworkStream myStream = client.GetStream();                    //得到网络流

            byte[] data2 = Encoding.Default.GetBytes("Hi,你好");           //首先把输入的字符串消息转换为字节
            myStream.Write(data2, 0, data2.Length);                         //向myStream 里写入数据
            myStream.Flush();                                               //刷新流中的数据
            myStream.Close();
        }
Beispiel #21
0
        void FixedUpdate()
        {
            try
            {
                // Receive the time gap between Unity and ROS
                if (this.networkStream.DataAvailable)
                {
                    byte[] byteArray = new byte[256];

                    if (networkStream.CanRead)
                    {
                        networkStream.Read(byteArray, 0, byteArray.Length);
                    }

                    string   message      = System.Text.Encoding.UTF8.GetString(byteArray);
                    string[] messageArray = message.Split(',');

                    if (messageArray.Length == 3)
                    {
                        SIGVerseLogger.Info("Time gap sec=" + messageArray[1] + ", msec=" + messageArray[2]);

                        SIGVerse.RosBridge.std_msgs.Header.SetTimeGap(Int32.Parse(messageArray[1]), Int32.Parse(messageArray[2]));
                    }
                    else
                    {
                        SIGVerseLogger.Error("Illegal message. Time gap message=" + message);
                    }
                }
            }
            catch (ObjectDisposedException exception)
            {
                SIGVerseLogger.Warn(exception.Message);
            }
        }
Beispiel #22
0
        public GameClient(TcpClient client)
        {
            netstream = client.GetStream();

            timer = new Stopwatch();

            byte[] message = new byte[4096];
            int msgsize = 0;

            while (true)
            {
                timer.Start();
                try { msgsize = netstream.Read(message, 0, 4096); }
                catch { break; } //socket error

                if (msgsize == 0)
                {

                    break; //client disconnected
                }

                //message received
                HandlePacket(message.Take(msgsize).ToArray());
            }

            GameServer.PlayerCount--;
            GConsole.WriteStatus("User '{0}' disconnected.", this.UserID);

            client.Close();
        }
    public void WorkerThread()
    {
        while (!isConnectedToServer)
        {
            Thread.Sleep(10);
        }

        while (isConnectedToServer)
        {
            if (!ns.CanRead)
            {
                break;
            }

            int len = ns.Read(buf, 0, buf.Length);
            if (len > 0)
            {
                taskFactory.StartNew(() => {
                    dataReceived(buf, 0, len);
                });
            }

            Thread.Sleep(1);
        }

//		taskFactory.StartNew (Task());
    }
Beispiel #24
0
        // Camera parameter を取得する
        static string GetCameraParameterInJson(string ipAddress)
        {
            TcpClient tcp = new TcpClient(ipAddress, SHOOTIMAGESERVER_PORT);

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

            // get parameter コマンドを送信
            string cmd = "PGT";

            byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd);
            ns.Write(cmdBytes, 0, cmdBytes.Length);

            // データを受信
            while (tcp.Client.Available == 0)
            {
            }
            byte[] rcvBytes = new byte[tcp.Client.Available];
            ns.Read(rcvBytes, 0, tcp.Client.Available);
            string rcvString = System.Text.Encoding.UTF8.GetString(rcvBytes);

            tcp.Close();
            return(rcvString);
        }
Beispiel #25
0
 private void ServerService()
 {
     _tcpListener.Start();
     Socket = _tcpListener.AcceptSocket();
     try
     {
         Stream = new NetworkStream(Socket);
         var buffer = new byte[1024];
         var commandInterpreter = new CommandInterpreter();
         while (true)
         {
             if (!Stream.DataAvailable) continue;
             var bytesRead = Stream.Read(buffer, 0, buffer.Length);
             var receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
             if (commandInterpreter.ExecuteCommand(receivedMessage))
             {
                 MessageBox.Show("Remote Client Disconnected");
                 break;
             }
         }
         Stream.Close();
         _tcpListener.Stop();
     }
     catch (Exception e)
     {
         MessageBox.Show("Something went wrong with the connection " + e.Message);
     }
 }
Beispiel #26
0
    // https://gist.github.com/danielbierwirth/0636650b005834204cb19ef5ae6ccedb
    public void ExchangePackets()
    {
        while (!exchangeStopRequested)
        {
            if (writer == null || reader == null)
            {
                continue;
            }
            string received = "";
            byte[] bytes    = new byte[client.SendBufferSize];
            int    recv     = 0;
            while (true)
            {
                recv      = stream.Read(bytes, 0, client.SendBufferSize);
                received += Encoding.UTF8.GetString(bytes, 0, recv);
                if (received.EndsWith("\n"))
                {
                    break;
                }
                // if (received.Length == 4096) break;
            }

            Debug.Log("Number of bytes " + received.Length);
            Debug.Log("Got " + received);
            System.Threading.Thread.Sleep(1000);
            // if (received == "empty\n") continue;
            latestRecievedMsg = received;
        }
    }
Beispiel #27
0
    public void ExchangePackets()
    {
        while (!exchangeStopRequested)
        {
            if (writer == null || reader == null)
            {
                continue;
            }
            exchanging = true;

            // writer.Write("request_pupil");
            // Debug.Log("Sent data!");
            string received = null;

#if UNITY_EDITOR
            byte[] bytes = new byte[client.SendBufferSize];
            int    recv  = 0;
            while (true)
            {
                recv      = stream.Read(bytes, 0, client.SendBufferSize);
                received += Encoding.UTF8.GetString(bytes, 0, recv);
                if (received.EndsWith("\n"))
                {
                    break;
                }
            }
#else
            received = reader.ReadLine();
#endif

            lastPacket = received;

            exchanging = false;
        }
    }
        public void Read(NetworkStream stream)
        {
            X = StreamHelper.ReadInt(stream);
            Z = StreamHelper.ReadInt(stream);
            Size = StreamHelper.ReadShort(stream);
            CoordinateArray = new short[Size];
            TypeArray = new byte[Size];
            MetadataArray = new byte[Size];

            for (int i = 0; i < Size; i++)
            {
                CoordinateArray[i] = StreamHelper.ReadShort(stream);
            }

            stream.Read(TypeArray, 0, Size);
            stream.Read(MetadataArray, 0, Size);
        }
Beispiel #29
0
 private string ReadMessage()
 {
     Byte[] data = new Byte[255];
     _stream = _client.GetStream();
     var length = _stream.Read(data, 0, 255);
     var message = System.Text.Encoding.ASCII.GetString(data, 0, length);
     return message;
 }
Beispiel #30
0
        internal static NewPayLoad ReadPayLoad(TcpClient clientSocket)
        {
            System.Net.Sockets.NetworkStream ns = clientSocket.GetStream();
            byte[] rcvLenBytesBB = new byte[4];

            //TODO: wait till max comm timeout

            while (!ns.DataAvailable)
            {
                //TODO: adaptive sleep
                // General.DoEvents();

                // TODO: try async call instead of loop and thread sleep - = much faster
                // meanwhile we can sleep 1
                Thread.Sleep(1);   //TODO 10 is too big how can we avoid? - change to 1 for super speed but check CPU spin on long requests
                if (!SocketConnected(clientSocket))
                {
                    throw new Exception("GingerSocket.GetResponse ERROR: Lost connection");
                }
            }
            ns.Read(rcvLenBytesBB, 0, 4);

            int rcvLen = ((rcvLenBytesBB[0]) << 24) + (rcvLenBytesBB[1] << 16) + (rcvLenBytesBB[2] << 8) + rcvLenBytesBB[3];

            int received = 0;

            byte[] rcvBytes = new byte[rcvLen + 4];

            //Copy len
            rcvBytes[0] = rcvLenBytesBB[0];
            rcvBytes[1] = rcvLenBytesBB[1];
            rcvBytes[2] = rcvLenBytesBB[2];
            rcvBytes[3] = rcvLenBytesBB[3];

            while (received < rcvLen)
            {
                received += ns.Read(rcvBytes, received + 4, rcvLen - received);
            }

            ns.Flush();

            NewPayLoad plRC = new NewPayLoad(rcvBytes);

            return(plRC);
        }
Beispiel #31
0
        public ServerPingData PingServer(string host, int port, out string error)
        {
            ServerPingData pingData = new ServerPingData();
            error = string.Empty;
            //Add timer to handle timeouts
            Timer timeoutTimer = new Timer(3000);
            //Attemp to contact the server
            try
            {
                client = new TcpClient(host, port);
                //Send a single message notifying the server we would like it's stats (0 is the ping request ID)
                data = new byte[1] { 0x00 };

                //Get a client stream for reading and writing
                stream = client.GetStream();

                //Send the message to the connected TcpServer.
                stream.Write(data, 0, data.Length);

                Debug.WriteLine("ServerPinger Sent: " + data.ToString());

                //Buffer to store the response bytes.
                data = new byte[256];

                //Read the first batch of the TcpServer response bytes
                int bytes = stream.Read(data, 0, data.Length);

                //TODO: This way of reading the recieved info is prone to errors
                //Someone needs to find a way to use methods like ReadString(), ReadByte(), etc for this section
                //This is a total hack and needs to be changed!
                pingData.Online = int.Parse(Encoding.ASCII.GetString(data).Substring(0,1));
                pingData.MaxOnline = int.Parse(Encoding.ASCII.GetString(data).Substring(1, 1));
                pingData.Description = Encoding.ASCII.GetString(data).Substring(2).Replace("\0","");
            }
            catch (Exception e)
            {
                error = e.Message;
                pingData.Error = true;
                Debug.WriteLine(e.ToString());
                if (e is SocketException)
                {
                    //Provide some better error messages
                    int id = (e as SocketException).ErrorCode;
                    if (id == 10061) //No connection could be made because the target machine actively refused it
                        error = "Target is online, however is not accessible.\n(Not running a server on that port, or blocked through a firewall)";
                    else if (id == 10060) //A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
                        error = "Connection timed out, could not connect.";
                }
            }
            finally
            {
                if (client != null)
                    client.Close();
            }
            return pingData;
        }
 static void Read(NetworkStream stream, byte[] buffer, int offset, int size)
 {
     while(size>0)
     {
         int read=stream.Read(buffer, offset, size);
         if(read==0) throw new Exception();
         size-=read;
         offset+=read;
     }
 }
 public void SendMessage(string message)
 {
     var messageBytes = Encoding.UTF8.GetBytes($"{message}\r\n");
     _stream = _tcpClient.GetStream();
     _stream.Write(messageBytes, 0, messageBytes.Length);
     var buffer = new byte[256];
     _stream.Read(buffer, 0, buffer.Length);
     var data = Encoding.UTF8.GetString(buffer).Trim('\0');
     Debug.WriteLine($"Response: {data}");
 }
        public void Connect(string username, string password)
        {
            if (_TcpClient.Connected == false)
            {
                _TcpClient.Connect(HOST, PORT);

                Prompt prompt = new Prompt();
                prompt.status = Status.Connected;
                this.ShowPrompt(prompt);
            }
            if (_ServerStream == null)
            {
                _ServerStream = _TcpClient.GetStream();
            }

            UserAccount usr = new UserAccount();
            usr.username = string.IsNullOrEmpty(username) ? "Guest" : username;
            usr.email = "*****@*****.**";
            string jstr = JS.Serialize<UserAccount>(usr);

            this.SendRaw(jstr);

            Thread task = new Thread(() =>
            {
                _ServerStream = _TcpClient.GetStream();

                try
                {
                    byte[] bytes = new byte[BUFFER_SIZE];
                    int bytesRead = _ServerStream.Read(bytes, 0, bytes.Length);
                    UserAccount user = JS.Deserialize<UserAccount>(bytes, bytesRead);

                    if (this.IsLoggedIn(user))
                    {
                        this._User = user;

                        Prompt prompt = new Prompt();
                        prompt.status = Status.LoggedIn;
                        this.ShowPrompt(prompt);

                        startChatListen();
                    }
                }
                catch(Exception ex)
                {
                    Prompt prompt = new Prompt();
                    prompt.status = (int)Status.LoggingError;
                    prompt.description = ex.Message;
                    this.ShowPrompt(prompt);
                }
            });
            _Threads.Add(task.GetHashCode(), task);
            task.Start();
        }
Beispiel #35
0
 public string read(NetworkStream ns)
 {
     byte[] buffer = new byte[socket.ReceiveBufferSize];
     while (true)
     {
         int bytesRead = ns.Read(buffer, 0, buffer.Length);
         string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
         if (dataReceived.Length > 0)
             return dataReceived;
     }
 }
        public void Connect(ServerSource server = ServerSource.Test)
        {
            _Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _Socket.Connect("livedata.americascup.com", (int)server);

            _Stream = new NetworkStream(_Socket, System.IO.FileAccess.Read);

            Action<byte[]> fillbuffer = b =>
            {
                int total = 0, read = 0;
                while ((read = _Stream.Read(b, total, b.Length - total)) > 0)
                {
                    total += read;
                }
            };

            Action receive = null;
            receive = new Action(() =>
             {
                 var header = new byte[15];
                 fillbuffer(header);

                 var c = BitConverter.ToUInt16(header, 13);
                 var body = new byte[c];
                 fillbuffer(body);

                 var crc = new byte[4];
                 fillbuffer(crc);

            #if DEBUG
                 if (header[0] != 0x47 || header[1] != 0x83)
                     Debug.WriteLine("Invalid message header");

                 uint cm = BitConverter.ToUInt32(crc, 0);
                 uint c1 = Crc32.Compute(header.Concat(body).ToArray());

                 if (c1 != cm)
                 {
                     Debug.WriteLine(string.Format("CRC check failed: {1} in message vs. {0} calculated", c1, cm));
                     string sheader = string.Join(" ", header.Select(b => b.ToString("X2")));
                     string sbody = string.Join(" ", body.Select(b => b.ToString("X2")));
                     string scrc = string.Join(" ", crc.Select(b => b.ToString("X2")));
                     Debug.Write(string.Format("Header: {0}\nBody: {1}\nCRC: {2}\n", sheader, sbody, scrc));
                 }
            #endif
                 Task.Factory.StartNew(() =>
                 {
                     if (OnMessage != null) OnMessage(header, body, crc);
                     Task.Factory.StartNew(receive);
                 });
             });

            Task.Factory.StartNew(receive);
        }
    private void ListenRequests()
    {
        // Create listener on localhost port 4002, the server will listen on that port.
        Int32 port = 4002;

        //Ignore IP Address
        System.Net.IPAddress localAddr = current_IP;

        try
        {
            tcpListener = new System.Net.Sockets.TcpListener(localAddr, port);
            tcpListener.Start();
            Debug.Log("Server is listening");
            Byte[] bytes = new Byte[1024];

            /* REFORMAT THIS */
            while (true)
            {
                using (connectedTcpClient = tcpListener.AcceptTcpClient())
                {
                    // Get a stream object for reading
                    using (stream = connectedTcpClient.GetStream())
                    {
                        int length;
                        // Read incoming stream of data, if there is data.
                        while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            //Debugger
                            Debug.Log("Listening for incoming requests");

                            //Read the data that was sent.
                            var data = new byte[length];
                            Array.Copy(bytes, 0, data, 0, length);
                            // Convert byte array to string message.
                            string clientMessage = Encoding.ASCII.GetString(data);
                            Debug.Log("clientMessage: " + clientMessage);

                            //Write an answer to the client: it's the current instruction.
                            string response = currentInstruction;
                            sendClient(response);
                            //var e = "hllo";
                            //e.ToString;
                        }
                    }
                }
            }
        }


        catch (System.Net.Sockets.SocketException socketException)
        {
            Debug.Log("SocketException " + socketException.ToString());
        }
    }
        public static string GetStreamData(NetworkStream stream)
        {
            var msg = new byte[1024];
              int byteCount;
              byteCount = stream.Read(msg, 0, msg.Length);
              if (byteCount == 0)
            return string.Empty;

              ASCIIEncoding encoder = new ASCIIEncoding();
              return
            encoder.GetString(msg, 0, byteCount);
        }
Beispiel #39
0
    public static void Main()
    {
        IPAddress  myIP         = IPAddress.Parse("127.0.0.1");
        IPEndPoint myIpEndPoint = new IPEndPoint(myIP, 8888);

        System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(myIpEndPoint);
        listener.Start();
        Console.WriteLine(
            "Listenを開始しました({0}:{1})。",
            ((IPEndPoint)listener.LocalEndpoint).Address,
            ((IPEndPoint)listener.LocalEndpoint).Port
            );

        System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
        Console.WriteLine(
            "クライアント({0}:{1})と接続しました。",
            ((IPEndPoint)client.Client.RemoteEndPoint).Address,
            ((IPEndPoint)client.Client.RemoteEndPoint).Port
            );

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

        System.Text.Encoding enc = System.Text.Encoding.UTF8;

        Queue <string> messages = new Queue <string>(510);

        while (ns.CanRead)
        {
            int    resSize            = 0;
            byte[] resBytes           = new byte[2048];
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            do
            {
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                ms.Write(resBytes, 0, resSize);
            } while (ns.DataAvailable);

            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            resMsg = resMsg.TrimEnd('\n');

            ms.Close();
            messages.Enqueue(resMsg);
            if (messages.Count > 500)
            {
                messages.Dequeue();
            }
            System.IO.StreamWriter sw = new System.IO.StreamWriter(@"FC2.log", false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.Write(string.Join("\n", messages.ToArray()));
            sw.Close();
            Console.WriteLine("{0}", resMsg);
        }
    }
        private void Recivir_Mensaje()
        {
            while(true)
            {
                StreamCliente = Cliente.GetStream();
                byte[] bit = new byte[140];
                StreamCliente.Read(bit, 0, bit.Length);
                mensaje = Encoding.ASCII.GetString(bit);
                Mensaje_REcivido();

            }
        }
        void ServerReadWrite()
        {
            while (true)
            {
                //				resMsg = null;
                ns              = client.GetStream();
                ns.ReadTimeout  = Timeout.Infinite;
                ns.WriteTimeout = Timeout.Infinite;

                bool disconnected = false;
                ms = new System.IO.MemoryStream();
                byte[] resBytes = new byte[256];
                int    resSize  = 0;
                do
                {
                    try
                    {
                        resSize = ns.Read(resBytes, 0, resBytes.Length);
                        if (resSize == 0)
                        {
                            disconnected = true;
                            Console.WriteLine("クライアントが切断しました。");
                            ServerThread.Abort();
                            break;
                        }
                        ms.Write(resBytes, 0, resSize);
                    }
                    catch
                    {
                        ;
                    }
                } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');

                resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                ms.Close();
                resMsg = resMsg.TrimEnd('\n');

                FromClientMessage = resMsg.Split(':');
                //				string rcvMsgNo = FromClientMessage[0] + ";" + FromClientMessage[1];
                //				string rcvMsg = FromClientMessage[2];
                //				PutServerText();
                if (!disconnected)
                {
                    string sendMsg   = resMsg.Length.ToString();
                    byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                    Console.WriteLine(sendMsg);
                }
            }
        }
Beispiel #42
0
        public string receiveClientName(TcpClient tcpClient)
        {
            String incomingMessage = "";
            String clientName      = "";
            bool   isRunning       = true;

            if (globalDataSet.DebugMode)
            {
                Debug.Write("Receive name of client" + "\n");
            }
            while (isRunning)
            {
                try
                {
                    System.Net.Sockets.NetworkStream ns = tcpClient.GetStream();
                    byte[] buffer = new byte[8192];

                    int data = ns.Read(buffer, 0, 1);
                    incomingMessage = System.Text.Encoding.ASCII.GetString(buffer, 0, data);
                    if (incomingMessage.Length != 0)
                    {
                        if (!incomingMessage.Equals(";"))
                        {
                            if (globalDataSet.DebugMode)
                            {
                                Debug.Write("Name: " + clientName + "\n");
                            }
                            clientName += incomingMessage;
                        }
                        else
                        {
                            isRunning = false;
                            return(clientName);
                        }
                    }
                }
                catch (System.IO.IOException ex)
                {
                    isRunning = false;
                    if (globalDataSet.DebugMode)
                    {
                        Debug.Write("Error in receiveClientName: " + ex);
                    }
                    return("");
                }
            }
            return("");
        }
Beispiel #43
0
    public void ExchangePackets()
    {
        // TODO: maybe sleep here somewhere, the loop rolls really fast
        while (!exchangeStopRequested)
        {
            if (writer == null || reader == null)
            {
                continue;
            }

            // writer.Write(request_msg);
            string received = null;

#if UNITY_EDITOR
            byte[] bytes = new byte[client.SendBufferSize];
            int    recv  = 0;
            while (true)
            {
                recv      = stream.Read(bytes, 0, client.SendBufferSize);
                received += Encoding.UTF8.GetString(bytes, 0, recv);
                if (received.EndsWith("\n"))
                {
                    break;
                }
                // if (received.Length == 4096) break;
            }
#endif

#if !UNITY_EDITOR
            received = reader.ReadLine();
#endif

            // received = Regex.Replace(received, @"\t|\n|\r", ""); // remove the ending \n nonon this takes super much time
            Debug.Log("Msg length " + received.Length);
            // Debug.Log("Got message: " + received);
            if (received == "ok\n")
            {
                request_msg = "x\n";
            }

            if (received == "empty\n")
            {
                continue;
            }
            latestRecievedMsg = received;
        }
    }
Beispiel #44
0
            //--
            //-- get data from the current network connection
            //--
            private string GetData(TcpClient tcp)
            {
                System.Net.Sockets.NetworkStream objNetworkStream = tcp.GetStream();

                if (objNetworkStream.DataAvailable)
                {
                    byte[] bytReadBuffer = null;
                    int    intStreamSize = 0;
                    bytReadBuffer = new byte[_intBufferSize + 1];
                    intStreamSize = objNetworkStream.Read(bytReadBuffer, 0, bytReadBuffer.Length);
                    System.Text.UTF8Encoding en = new System.Text.UTF8Encoding();
                    return(en.GetString(bytReadBuffer));
                }
                else
                {
                    return("");
                }
            }
Beispiel #45
0
    public void sendtcp(string sendMsg)
    {
        string ipOrHost = "127.0.0.1";

        int port = 8080;

        System.Net.Sockets.TcpClient tcp =
            new System.Net.Sockets.TcpClient(ipOrHost, port);
        Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。",
                          ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address,
                          ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port,
                          ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address,
                          ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port);
        System.Net.Sockets.NetworkStream ns = tcp.GetStream();

        ns.ReadTimeout  = 10000;
        ns.WriteTimeout = 10000;

        System.Text.Encoding enc = System.Text.Encoding.UTF8;
        byte[] sendBytes         = enc.GetBytes(sendMsg + '\n');
        ns.Write(sendBytes, 0, sendBytes.Length);
        Console.WriteLine(sendMsg);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        byte[] resBytes           = new byte[256];
        int    resSize            = 0;

        resSize = ns.Read(resBytes, 0, resBytes.Length);

        if (resSize == 0)
        {
            Console.WriteLine("サーバーが切断しました。");
        }

        string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

        ms.Close();
        //末尾の\nを削除
        resMsg = resMsg.TrimEnd('\n');
        Console.WriteLine(resMsg);

        //閉じる
        ns.Close();
        tcp.Close();
    }
Beispiel #46
0
        private void BtnRecibir_Click(object sender, EventArgs e)
        {
            System.Net.Sockets.NetworkStream stream = TCPCliente.GetStream();

            //Data reciving mechanism
            //Corrigue este metodo para que siempre este en escuchar y cuando llegue un mensaje lo puedas ver inmediatamente.
            if (stream.CanRead)                                                   //Preguntamos si es posible leer
            {
                if (stream.DataAvailable)                                         //Preguntamos si hay algo por leer
                {
                    Byte[] data         = new Byte[TCPCliente.ReceiveBufferSize]; //Buffer del tamaño de lo que se recibio
                    string responseData = "";                                     //String to store the response ASCII representation

                    Int32 bytes = stream.Read(data, 0, data.Length);
                    responseData   = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                    textBox2.Text += "Received " + responseData;
                }
            }
        }
Beispiel #47
0
 static void SocketToWritePipe(System.Net.Sockets.NetworkStream networkStream, StreamString ss)
 {
     Task.Factory.StartNew(() =>
     {
         byte[] netReadBuffer = new byte[1024];
         int charsread        = 0;
         while (true)
         {
             if (networkStream.CanRead)
             {
                 charsread = networkStream.Read(netReadBuffer, 0, 250);
                 String s  = Convert.ToBase64String(netReadBuffer, 0, charsread);
                 if (charsread > 0)
                 {
                     Console.WriteLine("SocketToWritePipe: Decoded " + charsread + " / Encoded " + s.Length);
                     ss.WriteString(s);
                 }
             }
         }
     });
 }
Beispiel #48
0
 // Процедура чтения данных от сервера
 private void Read(object o)
 {
     while (true)
     {
         if (stream == null)
         {
             continue;
         }
         int    i;
         Byte[] bytes = new Byte[256];
         String data  = null;
         if (stream.CanRead)
         {
             // Считываем данные из потока
             i    = stream.Read(bytes, 0, bytes.Length);
             data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
             // Добавляем считанную строку в лог
             this.multiLineBox.Text += data;
         }
     }
 }
Beispiel #49
0
    // Update is called once per frame
    void Update()
    {
        //↓にC++に送るデータをぶち込む
        //今回は経過時間
        if (goldfish0.moterflag == 1 || goldfish1.moterflag == 1 || goldfish2.moterflag == 1 || goldfish3.moterflag == 1 || goldfish4.moterflag == 1)
        {
            data = "1";
        }
        else
        {
            data = "0";
        }
        //Debug.Log(goldfish0.moterflag.ToString());
        //data = "1.0000";
        //data = Time.time.ToString();

        //タイムアウト設定
        ns.ReadTimeout  = 10000;
        ns.WriteTimeout = 10000;

        //サーバーにデータを送信
        //文字列をByte型配列に変換
        System.Text.Encoding enc = System.Text.Encoding.UTF8;
        byte[] sendBytes         = enc.GetBytes(data + '\n');
        //データを送信する
        ns.Write(sendBytes, 0, sendBytes.Length);
        //Debug.Log(data);


        //サーバーから送られたデータを受信する
        //今回は一周期分の時間が送られてくる。
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        byte[] resBytes           = new byte[256];
        int    resSize            = 256;

        //データを受信
        resSize = ns.Read(resBytes, 0, resBytes.Length);
        //受信したデータを蓄積
        ms.Write(resBytes, 0, resSize);
        //受信したデータを文字列に変換
        resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
        ms.Close();
        //末尾の\nを削除
        resMsg = resMsg.TrimEnd('\n');
        //Debug.Log(resMsg);

        //データをセンサの数だけ分割
        string[] str = resMsg.Split(' ');

        for (int i = 0; i < str.Length; i++)
        {
            //int型に変換
            num[i] = int.Parse(str[i]);
            //Debug.Log(num[i]);
        }


        //書き込みを行うセンサー値を取得

        /*
         * SenserVal[SenserCount] = num[1];
         * Debug.Log(SenserVal[SenserCount]);
         * SenserCount += 1;
         */

        //rb.MoveRotation(Quaternion.AngleAxis(45f, Vector3.forward))Debug.Log(num);

        //スペース押すと閉じる
        if (Input.GetKey(KeyCode.Space))
        {
            //センサー値をCSV形式でエクスポート
            //logSave(SenserVal, "Test");

            ns.Close();
            tcp.Close();
            Debug.Log("切断しました。");
        }
    }
Beispiel #50
0
        private static CS422.WebRequest BuildRequest(TcpClient client)
        {
            MemoryStream data     = new MemoryStream();
            StreamReader sr       = new StreamReader(data);
            DateTime     start    = DateTime.Now;
            TimeSpan     duration = TimeSpan.FromSeconds(10);

            int  currentRead = -1;
            long totalRead   = 0;

            byte[] buffer = new byte[1024];

            // flags for peices of the request
            bool goodRequest    = false;
            bool goodUrl        = false;
            bool goodVersion    = false;
            bool goodMethod     = false;
            int  urlIndex       = -1;
            int  lengthOfMethod = 0;

            // list of regex rules to match different parts of the request.
            //Regex requestBeginMatch = new Regex("^GET /[^ ]* HTTP/1.1");
            Regex requestEndMatch = new Regex("\r\n\r\n");

            //Regex requestUriMatch = new Regex("/[^ ]* ");

            System.Net.Sockets.NetworkStream stream = client.GetStream();
            stream.ReadTimeout = 2000;

            // peices needed to build the request object
            string method;
            string url;
            string version;
            ConcurrentDictionary <string, string> headers = new ConcurrentDictionary <string, string>();

            while (currentRead != 0 && totalRead < HeadersTimeout)
            {
                // first thing check to make sure the entire thing hasn't taken too long to read
                if (DateTime.Now - start > duration)
                {
                    // took to long, abort

                    return(null);
                }
                if (totalRead > firstLineTimeout && !goodVersion)
                {
                    Console.WriteLine("URL TO LONG");
                    return(null);
                }
                //read one KB from the client stream
                try{
                    currentRead = stream.Read(buffer, 0, 1024);
                }
                catch (IOException ex)
                {
                    // took too long to read any data;

                    Console.WriteLine("client took too long to respond");
                    return(null);
                }

                //store the information read from the client in our memory buffer
                data.Write(buffer, 0, currentRead);

                //update how much in total we have received from the client
                totalRead += currentRead;

                // if we have more than 4 bytes check method
                if (totalRead >= 4 && goodMethod == false)
                {
                    // bad method
                    if (!checkMethod(data, out lengthOfMethod))
                    {
                        return(null);
                    }
                    else
                    {
                        goodMethod = true;
                    }
                }

                // begin checking for a valid http request after 16 bytes
                if (totalRead >= 16 && goodMethod == true)
                {
                    // first check url
                    if (goodUrl == false)
                    {
                        urlIndex = UrlEndIndex(data, 3);
                        if (urlIndex > 0)
                        {
                            // we have a good url
                            goodUrl = true;
                        }
                    }

                    if (goodUrl == true)
                    {
                        if (checkVersion(data, urlIndex))
                        {
                            goodVersion = true;
                        }
                    }

                    if (goodVersion)
                    {
                        data.Position = 0;
                        string d = sr.ReadToEnd();
                        if (requestEndMatch.IsMatch(d))
                        {
                            goodRequest = true;
                            currentRead = 0;
                        }
                    }
                    else
                    {
                        if (totalRead > urlIndex + 10 && goodUrl)
                        {
                            // bad version


                            return(null);
                        }
                    }
                }
            }

            if (totalRead + 100 >= HeadersTimeout)
            {
                Console.WriteLine("headers were too big");
            }
            if (goodRequest)
            {
                //if we found a good request build and return the web request object (also need to get the header stuff

                // here we need to build the request stuff soooooooooo
                string dataAsString = System.Text.Encoding.ASCII.GetString(data.ToArray());

                method  = dataAsString.Substring(0, lengthOfMethod);
                url     = dataAsString.Substring(lengthOfMethod, urlIndex - lengthOfMethod);
                version = dataAsString.Substring(urlIndex, 11);
                Console.WriteLine(dataAsString);
                // now the fun begins, we need to read all the headers in to the dictionary
                // where is the begginging on of the headers;
                string[] peices = dataAsString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                for (int i = 1; i < peices.Length; i++)
                {
                    if (peices[i] != "")
                    {
                        string[] header = peices[i].Split(':');
                        headers.TryAdd(header[0].ToLower(), header[1]);
                    }
                    else
                    {
                        i = peices.Length + 1;
                    }
                }

                // okay now we just need to set the stream to the right place
                data.Position = requestEndMatch.Matches(dataAsString)[0].Index + 4;

                // finally let's build that request object like a boss;
                return(new CS422.WebRequest(data, stream, headers, method, url, version, stream));
            }
            else
            {
                //request was bad close the client return null

                return(null);
            }
        }
        /// <summary>
        /// 指定IPアドレスのカメラのプレビュー画像データを取得する
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public static byte[] GetPreviewImage(string ipAddress)
        {
            TcpClient tcp = new TcpClient(ipAddress, SHOOTIMAGESERVER_PORT);

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

            // get preview image コマンドを送信
            string cmd = "PRV";

            byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd);
            ns.Write(cmdBytes, 0, cmdBytes.Length);

            // データを受信
            ulong        sum         = 0;
            ulong        bytesToRead = 0;
            MemoryStream ms          = new MemoryStream();

            do
            {
                if (tcp.Available == 0)
                {
                    continue;                       // Retry
                }
                byte[] rcvBytes = new byte[tcp.Client.Available];
                int    resSize  = 0;
                try {
                    resSize = ns.Read(rcvBytes, 0, rcvBytes.Length);
                } catch (IOException e) {
                    if (e.InnerException is SocketException)
                    {
                        var socketException = e.InnerException as SocketException;
                        if (socketException.SocketErrorCode == SocketError.TimedOut)
                        {
                            resSize = 0;                                // 再試行させる
                        }
                        else
                        {
                            throw e;
                        }
                    }
                    else
                    {
                        throw e;
                    }
                }
                ms.Write(rcvBytes, 0, resSize);
                if ((bytesToRead == 0) && (ms.Length >= 4))
                {
                    // 先頭の4バイトには、次に続くデータのサイズが書かれている
                    byte[] buffer = ms.GetBuffer();
                    bytesToRead = ((ulong)buffer[0]) | ((ulong)buffer[1] << 8) | ((ulong)buffer[2] << 16) | ((ulong)buffer[3] << 24);
                }
                sum += (ulong)resSize;
            } while (sum < bytesToRead + 4);
            ms.Close();
            ns.Close();
            tcp.Close();
            return(ms.GetBuffer().Skip(4).ToArray());
        }
Beispiel #52
0
    public static void Main()
    {
        Console.WriteLine("入力してください");
        string sendMsg = Console.ReadLine();

        if (sendMsg == null || sendMsg.Length == 0)
        {
            return;
        }

        string ipOrHost = "127.0.0.1";
        int    port     = 2001;


        System.Net.Sockets.TcpClient tcp =
            new System.Net.Sockets.TcpClient(ipOrHost, port);
        Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。",
                          ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address,
                          ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port,
                          ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address,
                          ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port);
        System.Net.Sockets.NetworkStream ns = tcp.GetStream();

        ns.ReadTimeout  = 10000;
        ns.WriteTimeout = 10000;


        System.Text.Encoding enc = System.Text.Encoding.UTF8;
        byte[] sendBytes         = enc.GetBytes(sendMsg + '\n');

        ns.Write(sendBytes, 0, sendBytes.Length);
        Console.WriteLine(sendMsg);


        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        byte[] resBytes           = new byte[256];
        int    resSize            = 0;

        do
        {
            resSize = ns.Read(resBytes, 0, resBytes.Length);

            if (resSize == 0)
            {
                Console.WriteLine("サーバーが切断しました。");
                break;
            }

            ms.Write(resBytes, 0, resSize);
        } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');

        string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

        ms.Close();

        resMsg = resMsg.TrimEnd('\n');
        Console.WriteLine(resMsg);
        ns.Close();
        tcp.Close();
        Console.WriteLine("切断しました。");

        Console.ReadLine();
    }
Beispiel #53
0
        static void Main(string[] args)
        {
            // Loading SyncshooterDefs
            var defs = SyncshooterDefs.Deserialize(@"..\..\syncshooterDefs.json");

            // TEST
            defs.Serialize(@"..\..\syncshooterDefs_copy.json");

            // UDP マルチキャストを開く
            MultiCastClient mcastClient = new MultiCastClient(MCAST_GRP, MCAST_PORT);

            if (mcastClient.Open() == false)
            {
                return;
            }
            //mcastClient.SendCommand( "SDW" );	// TEST

            // 接続しているラズパイのアドレスとポートを列挙する
            var mapIPvsPort = GetConectedHostAddress(mcastClient);

            // Camera parameter を取得する
            Console.Error.WriteLine("Get and save camera parameters...");
            foreach (var pair in mapIPvsPort)
            {
                IPAddress adrs = pair.Key;
                string    text = GetCameraParameterInJson(adrs.ToString());
                Console.WriteLine("{0}", text);
                var    param = JsonConvert.DeserializeObject <CameraParam>(text);
                string path  = string.Format(@"..\..\cameraParam_{0}.json", adrs.ToString());
                param.Serialize(path);
            }

            // Preview image の取得
            Console.Error.WriteLine("Previewing...");
            foreach (var pair in mapIPvsPort)
            {
                IPAddress adrs = pair.Key;
                TcpClient tcp  = new TcpClient(adrs.ToString(), SHOOTIMAGESERVER_PORT);
                System.Net.Sockets.NetworkStream ns = tcp.GetStream();
                ns.ReadTimeout  = 10000;
                ns.WriteTimeout = 10000;
                Console.WriteLine("IP Address: {0}", adrs);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                // get preview image コマンドを送信
                string cmd      = "PRV";
                byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd);
                ns.Write(cmdBytes, 0, cmdBytes.Length);

                // データを受信
                while (ns.DataAvailable == false)
                {
                }
                ulong sum           = 0;
                ulong bytes_to_read = 0;
                do
                {
                    byte[] rcvBytes = new byte[tcp.Client.Available];
                    int    resSize  = ns.Read(rcvBytes, 0, rcvBytes.Length);
                    if (sum == 0)
                    {
                        // 先頭の4バイトには、次に続くデータのサイズが書かれている
                        bytes_to_read = ((ulong)rcvBytes[0]) | ((ulong)rcvBytes[1] << 8) | ((ulong)rcvBytes[2] << 16) | ((ulong)rcvBytes[3] << 24);
                        Console.WriteLine("bytes_to_read = {0}", bytes_to_read);
                    }
                    sum += (ulong)resSize;
                    ms.Write(rcvBytes, 0, resSize);
                } while (sum < bytes_to_read + 4);
                Console.WriteLine("size = {0}", (int)sum - 4);
                ms.Close();

                String path = string.Format("preview_{0}.bmp", adrs.ToString());
                using (var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) {
                    fs.Write(ms.GetBuffer(), 4, (int)sum - 4);
                }

                ns.Close();
                tcp.Close();
            }

            //
            // Full image (JPG) の取得
            // Multicast で 撮影コマンドを送信
            mcastClient.SendCommand("SHJ");
            Console.Error.WriteLine("Capturing JPEG...");
            // Full image の取得
            foreach (var pair in mapIPvsPort)
            {
                IPAddress adrs = pair.Key;
                TcpClient tcp  = new TcpClient(adrs.ToString(), SHOOTIMAGESERVER_PORT);
                System.Net.Sockets.NetworkStream ns = tcp.GetStream();
                ns.ReadTimeout  = 10000;
                ns.WriteTimeout = 10000;
                Console.WriteLine("IP Address: {0}", adrs);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                // full image 取得コマンドを送信
                string cmd      = "IMG";
                byte[] cmdBytes = System.Text.Encoding.UTF8.GetBytes(cmd);
                ns.Write(cmdBytes, 0, cmdBytes.Length);

                // データを受信
                while (ns.DataAvailable == false)
                {
                }
                ulong sum           = 0;
                ulong bytes_to_read = 0;
                do
                {
                    byte[] rcvBytes = new byte[tcp.Client.Available];
                    int    resSize  = ns.Read(rcvBytes, 0, rcvBytes.Length);
                    if (sum == 0)
                    {
                        // 先頭の4バイトには、次に続くデータのサイズが書かれている
                        bytes_to_read = ((ulong)rcvBytes[0]) | ((ulong)rcvBytes[1] << 8) | ((ulong)rcvBytes[2] << 16) | ((ulong)rcvBytes[3] << 24);
                        Console.WriteLine("bytes_to_read = {0}", bytes_to_read);
                    }
                    sum += (ulong)resSize;
                    ms.Write(rcvBytes, 0, resSize);
                } while (sum < bytes_to_read + 4);
                Console.WriteLine("size = {0}", (int)sum - 4);
                ms.Close();

                String path = string.Format("full_{0}.jpg", adrs.ToString());
                using (var fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) {
                    fs.Write(ms.GetBuffer(), 4, (int)sum - 4);
                }

                ns.Close();
                tcp.Close();
            }

            mcastClient.Close();
        }
Beispiel #54
0
        public void receiveFromRobotController()
        {
            String incomingMessage     = "";
            String incomingMessageTemp = "";

            String[]  msgArray       = new String[] { "", "" };
            bool      commandMessage = false;
            bool      normalMessage  = false;
            bool      itsACommand    = false;
            TcpClient tcpClientRobot;

            //clientList.TryGetValue("RobotController", out tcpClientRobot);
            System.Net.Sockets.NetworkStream ns = networkStream; //tcpClientRobot.GetStream();
            byte[] buffer = new byte[8192];


            while (this.shutDown == false)
            {
                try
                {
                    //if(globalDataSet.DebugMode) Debug.Write("Received from server: " + incomingMessage + "\n");
                    int data = ns.Read(buffer, 0, 1);
                    incomingMessage = System.Text.Encoding.ASCII.GetString(buffer, 0, data);

                    if (incomingMessage.Length != 0)
                    {
                        incomingMessageTemp += incomingMessage;
                        if (!incomingMessage.Equals(":") && commandMessage)
                        {
                            itsACommand  = true;
                            msgArray[1] += incomingMessage;
                        }

                        if (!incomingMessage.Equals(":") && !commandMessage)
                        {
                            normalMessage = true;
                        }
                        // Check if msg should be read as command
                        if (incomingMessage.Equals(":") && !commandMessage)
                        {
                            commandMessage = true;
                        }
                        else if (incomingMessage.Equals(":") && commandMessage)
                        {
                            if (itsACommand)
                            {
                                normalMessage = false;
                            }
                            if (!itsACommand)
                            {
                                normalMessage = true;
                            }
                            commandMessage = false;
                        }

                        // Read message as normal characters
                        if (!incomingMessage.Equals(";") && !commandMessage && normalMessage)
                        {
                            msgArray[0] += incomingMessage;
                            itsACommand  = false;
                        }
                        else if (incomingMessage.Equals(";") && !commandMessage && normalMessage)
                        {
                            normalMessage = false;
                            if (this.statusChangedEvent != null)
                            {
                                this.statusChangedEvent(this.communicationName + ": Message received from Client - " + incomingMessage);
                            }

                            // TODO: Validate the length of incoming message and the content to request resend

                            // Fire the receive event and save sensor values to database
                            if (this.messageReceivedEvent != null)
                            {
                                this.messageReceivedEvent(msgArray);
                            }
                            //if (this.tunnelingMessage != null) this.tunnelingMessage(incomingMessageTemp);
                            // Test to use one thread for tunneling to client and to filtering...
                            //sendToPhone(incomingMessageTemp);
                            //if(globalDataSet.DebugMode) Debug.Write("Message received: " + incomingMessageTemp + "\n");
                            msgArray            = new String[] { "", "" };
                            incomingMessageTemp = "";
                        }
                    }
                }
                catch (System.IO.IOException ex)
                {
                    // TODO Validate shutdown implementation
                    this.shutDown = true;
                }
            }
        }
Beispiel #55
0
    public static void Main()
    {
        IPAddress  myIP         = IPAddress.Parse("127.0.0.1");
        IPEndPoint myIpEndPoint = new IPEndPoint(myIP, 8888);

        System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(myIpEndPoint);
        listener.Start();
        Console.WriteLine(
            "Listenを開始しました({0}:{1})。",
            ((IPEndPoint)listener.LocalEndpoint).Address,
            ((IPEndPoint)listener.LocalEndpoint).Port
            );

        System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
        Console.WriteLine(
            "クライアント({0}:{1})と接続しました。",
            ((IPEndPoint)client.Client.RemoteEndPoint).Address,
            ((IPEndPoint)client.Client.RemoteEndPoint).Port
            );

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

        System.Text.Encoding enc = System.Text.Encoding.UTF8;

        int            commentNo = 0;
        Queue <string> messages  = new Queue <string>(510);

        while (ns.CanRead)
        {
            int    resSize            = 0;
            byte[] resBytes           = new byte[2048];
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            do
            {
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                ms.Write(resBytes, 0, resSize);
            } while (ns.DataAvailable);

            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            resMsg = resMsg.TrimEnd('\n');
            Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(resMsg);
            bool isContainTip = dic.ContainsKey("tip_username");
            commentNo++;
            if (isContainTip)
            {
                resMsg = commentNo.ToString() + "\t" + dic["time"].Replace("\t", " ") + "\t" + dic["username"].Replace("\t", " ") + "\t" + dic["comment"].Replace("\t", " ") + "\t" + "1";
            }
            else
            {
                resMsg = commentNo.ToString() + "\t" + dic["time"].Replace("\t", " ") + "\t" + dic["username"].Replace("\t", " ") + "\t" + dic["comment"].Replace("\t", " ") + "\t" + "0";
            }
            ms.Close();
            messages.Enqueue(resMsg);
            if (messages.Count > 500)
            {
                messages.Dequeue();
            }
            try {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(@"FC2.log", false, System.Text.Encoding.GetEncoding("utf-8"));
                sw.Write(string.Join("\n", messages.ToArray()));
                sw.Close();
            } catch (Exception e) {
                Console.WriteLine("System.IO.StreamWriter: " + e.ToString());
            }
            Console.WriteLine("{0}", resMsg);
        }
    }
Beispiel #56
0
    public static void Main()
    {
        //サーバーに送信するデータを入力してもらう
        Console.WriteLine("文字列を入力し、Enterキーを押してください。");
        string sendMsg = Console.ReadLine();

        //何も入力されなかった時は終了
        if (sendMsg == null || sendMsg.Length == 0)
        {
            return;
        }

        //サーバーのIPアドレス(または、ホスト名)とポート番号
        string ipOrHost = "127.0.0.1";
        //string ipOrHost = "localhost";
        int port = 2001;

        //TcpClientを作成し、サーバーと接続する
        System.Net.Sockets.TcpClient tcp =
            new System.Net.Sockets.TcpClient(ipOrHost, port);
        Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。",
                          ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address,
                          ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port,
                          ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address,
                          ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port);

        //NetworkStreamを取得する
        System.Net.Sockets.NetworkStream ns = tcp.GetStream();

        //読み取り、書き込みのタイムアウトを10秒にする
        //デフォルトはInfiniteで、タイムアウトしない
        //(.NET Framework 2.0以上が必要)
        ns.ReadTimeout  = 10000;
        ns.WriteTimeout = 10000;

        //サーバーにデータを送信する
        //文字列をByte型配列に変換
        System.Text.Encoding enc = System.Text.Encoding.UTF8;
        byte[] sendBytes         = enc.GetBytes(sendMsg + '\n');
        //データを送信する
        ns.Write(sendBytes, 0, sendBytes.Length);
        Console.WriteLine(sendMsg);

        //サーバーから送られたデータを受信する
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        byte[] resBytes           = new byte[256];
        int    resSize            = 0;

        do
        {
            //データの一部を受信する
            resSize = ns.Read(resBytes, 0, resBytes.Length);
            //Readが0を返した時はサーバーが切断したと判断
            if (resSize == 0)
            {
                Console.WriteLine("サーバーが切断しました。");
                break;
            }
            //受信したデータを蓄積する
            ms.Write(resBytes, 0, resSize);
            //まだ読み取れるデータがあるか、データの最後が\nでない時は、
            // 受信を続ける
        } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
        //受信したデータを文字列に変換
        string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

        ms.Close();
        //末尾の\nを削除
        resMsg = resMsg.TrimEnd('\n');
        Console.WriteLine(resMsg);

        //閉じる
        ns.Close();
        tcp.Close();
        Console.WriteLine("切断しました。");

        Console.ReadLine();
    }
Beispiel #57
0
        //接続ボタン
        void ClientMode()
        {
            m_ActiveRecv           = true;
            timerReconnect.Enabled = false;

            string strSrcIP = textBoxSrcIp.Text;
            int    sSrcPort = Int32.Parse(textBoxSrcPort.Text);
            string strDstIP = textBoxDstIp.Text;
            int    sDstPort = Int32.Parse(textBoxDstPort.Text);

            try
            {
                localSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                localSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                var local = new System.Net.IPEndPoint(IPAddress.Parse(strSrcIP), sSrcPort);
                localSocket.Bind(local);

                //TcpClientを作成し、サーバーと接続する
                m_tcp        = new System.Net.Sockets.TcpClient();
                m_tcp.Client = localSocket;
                m_tcp.Connect(strDstIP, sDstPort);
                listBox1.Items.Add("接続成功");
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.TopIndex      = listBox1.SelectedIndex;

                //NetworkStreamを取得する
                m_ns = m_tcp.GetStream();
                //読み取り、書き込みのタイムアウトを10秒にする
                m_ns.ReadTimeout  = 1000;
                m_ns.WriteTimeout = 1000;

                m_thread = new Thread(new ThreadStart(() =>
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    byte[] resBytes           = new byte[65536];
                    int resSize = 0;
                    do
                    {
                        try
                        {
                            //データの一部を受信する
                            resSize = m_ns.Read(resBytes, 0, resBytes.Length);
                            //Readが0を返した時はサーバーが切断したと判断
                            if (resSize != 0)
                            {
                                //受信したデータを蓄積する
                                ms.Write(resBytes, 0, resSize);
                                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                                // 受信を続ける
                                Invoke(new ListAddDelegate(OutputLogRecv));
                            }
                            else
                            {
                                //切断
                                break;
                            }
                        }
                        catch (ArgumentNullException e1)
                        {
                        }
                        catch (ArgumentOutOfRangeException e2)
                        {
                        }
                        catch (InvalidOperationException e3)
                        {
                            //切断
                            break;
                        }
                        catch (IOException e4)
                        {
                        }
                    } while (m_ActiveRecv);
                    //受信したデータを文字列に変換
                    ms.Close();
                    m_ns.Close();
                    m_ns = null;
                    m_tcp.Close();
                    m_tcp = null;
                    localSocket.Close();
                    localSocket = null;
                    try
                    {
                        Invoke(new ListAddDelegate(ErrDiscconect));
                    }
                    catch (Exception)
                    {
                    }
                }));

                m_thread.Start();

                buttonConnect.Enabled    = false;
                buttonSend.Enabled       = true;
                buttonDisconnect.Enabled = true;

                //連続送信する場合タイマきどう
                if (checkBoxReSend.Checked == true)
                {
                    timerResend.Interval = Int32.Parse(textBox1.Text);
                    timerResend.Enabled  = true;
                }
            }
            catch (Exception)
            {
                listBox1.Items.Add("接続失敗");
                listBox1.SelectedIndex = listBox1.Items.Count - 1;
                listBox1.TopIndex      = listBox1.SelectedIndex;
                if (m_ns != null)
                {
                    m_ns.Close();
                }
                if (m_tcp != null)
                {
                    m_tcp.Close();
                }
                if (localSocket != null)
                {
                    localSocket.Close();
                }
            }
            //再接続時間が設定されている場合、再接続
            if (checkBoxReconnect.Checked)
            {
                timerReconnect.Interval = Int32.Parse(textBoxReconnectTime.Text);
                timerReconnect.Enabled  = true;

                buttonConnect.Enabled    = false;
                buttonDisconnect.Enabled = true;
            }
        }
Beispiel #58
0
    public static void Main()
    {
        // ListenするIPアドレス
        string ipString = "127.0.0.1";

        System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

        // Listenするポート番号
        int port = 2001;

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

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

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

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

        // 読取り,書き込みのタイムアウトを10秒にする
        // デフォルトはInfiniteでタイムアウトしない
        // (.NET Framework 2.0以上が必要
        ns.ReadTimeout  = 10000;
        ns.WriteTimeout = 10000;

        // クライアントから送られたデータを受信する
        System.Text.Encoding enc = System.Text.Encoding.UTF8;
        bool disconnected        = false;

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        byte[] resBytes           = new byte[256];
        int    resSize            = 0;

        do
        {
            // データの一部を受信する
            resSize = ns.Read(resBytes, 0, resBytes.Length);
            // Readが0を返した時はクライアントが切断したと判断
            if (resSize == 0)
            {
                disconnected = true;
                Console.WriteLine("クライアントが切断しました.");
                break;
            }
            // 受信したデータを蓄積する
            ms.Write(resBytes, 0, resSize);
            // まだ読み取れるデータがあるか,データの最後が\n出ない時は,受信を続ける
        } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');

        // 受信したデータを文字列に変換
        string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

        ms.Close();

        // 末尾の\nを削除
        resMsg = resMsg.TrimEnd('\n');
        Console.WriteLine(resMsg);

        if (!disconnected)
        {
            // クライアントにデータを送信する
            // クライアントに送信する文字列を作成
            string sendMsg = resMsg.Length.ToString();
            // 文字列をByte型配列に変換
            byte[] sendBytes = enc.GetBytes(sendMsg + "\n");
            // データを送信する
            ns.Write(sendBytes, 0, sendBytes.Length);
            Console.WriteLine(sendMsg);
        }

        // 閉じる
        ns.Close();
        client.Close();
        Console.WriteLine("クライアントとの接続を閉じました.");

        // リスナを閉じる
        listener.Stop();
        Console.WriteLine("Listenerを閉じました.");
        Console.ReadLine();
    }
Beispiel #59
0
    public static void Main()
    {
        string ipString = "127.0.0.1";

        System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

        int port = 2001;

        System.Net.Sockets.TcpListener listener =
            new System.Net.Sockets.TcpListener(ipAdd, port);

        listener.Start();

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


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

        // NetworkStreamを取得データの流れ
        System.Net.Sockets.NetworkStream ns = client.GetStream();

        ns.ReadTimeout  = 10000;
        ns.WriteTimeout = 10000;

        System.Text.Encoding enc = System.Text.Encoding.UTF8;
        bool disconnected        = false;

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        byte[] resBytes = new byte[256];
        int    resSize  = 0;


        do
        {
            //データの一部を受信する
            resSize = ns.Read(resBytes, 0, resBytes.Length);
            //Readが0を返した時はクライアントが切断したと判断
            if (resSize == 0)
            {
                disconnected = true;
                Console.WriteLine("クライアントが切断しました。");
                break;
            }
            //受信したデータを蓄積する
            ms.Write(resBytes, 0, resSize);
            //まだ読み取れるデータがあるか、データの最後が\nでない時は、
            // 受信を続ける
        } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');

        //受信したデータを文字列に変換
        string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

        ms.Close();

        resMsg = resMsg.TrimEnd('\n');
        Console.WriteLine(resMsg);

        if (!disconnected)
        {
            //クライアントにデータを送信する
            //クライアントに送信する文字列を作成
            string sendMsg = resMsg.Length.ToString();

            //文字列をByte型配列に変換
            byte[] sendBytes = enc.GetBytes(sendMsg + '\n');

            //データを送信する
            ns.Write(sendBytes, 0, sendBytes.Length);
            Console.WriteLine(sendMsg);
        }

        ns.Close();
        client.Close();
        Console.WriteLine("クライアントとの接続を閉じました。");

        listener.Stop();
        Console.WriteLine("Listenerを閉じました。");

        Console.ReadLine();
    }
        static void Main(string[] args)
        {
            //Connect
            TcpClient tcpClient = new TcpClient();

            tcpClient.Connect("localhost", 3334);
            MessageSender   messageSender   = new MessageSender(tcpClient.Session);
            MessageReceiver messageReceiver = new MessageReceiver(tcpClient.Session);
            MessageExecutor messageExecutor =
                new MessageExecutor(messageSender, messageReceiver, new InstantTaskScheduler());

            messageExecutor.Configuration.DefaultTimeout = 10000;
            var notificationListener = new NotificationListener();

            messageReceiver.AddListener(-1, notificationListener);

            //auth
            AuthorizeHciRequest request = new AuthorizeHciRequest();

            request.ClientId = -1;
            request.Locale   = "en-US";
            var future = messageExecutor.Submit <AuthorizeHciResponse>(request);

            future.Wait();
            AuthorizeHciResponse AuthorizeHciResponse = future.Value;
            int clientId = AuthorizeHciResponse.ClientId;

            System.Console.WriteLine("AuthorizeHciResponse precessed");

            //login
            LoginRequest loginRequest = new LoginRequest();

            loginRequest.UserLogin    = "******";
            loginRequest.UserPassword = "******";
            loginRequest.ClientId     = clientId;
            var loginResponcetask = messageExecutor.Submit <LoginResponse>(loginRequest);

            loginResponcetask.Wait();

            // Id of the emu-copter is 2
            var vehicleToControl = new Vehicle {
                Id = 3
            };

            TcpClientt.TcpListener server = new TcpClientt.TcpListener(IPAddress.Any, 8080);
            server.Start(); // run server
            byte[] ok = new byte[100];
            ok = Encoding.Default.GetBytes("ok");
            while (true) // бесконечный цикл обслуживания клиентов
            {
                TcpClientt.TcpClient     client = server.AcceptTcpClient();
                TcpClientt.NetworkStream ns     = client.GetStream();
                while (client.Connected)
                {
                    byte[] msg   = new byte[100];
                    int    count = ns.Read(msg, 0, msg.Length);
                    Console.Write(Encoding.Default.GetString(msg, 0, count));
                    string allMessage  = Encoding.Default.GetString(msg);
                    string result      = allMessage.Substring(0, count - 1);
                    var    commandName = result.ToString().Split(":")[0];


                    switch (commandName)
                    {
                    case "takeoff_command":
                    {
                        Console.Write("got command: {0}", commandName);

                        SendCommandRequest takeoff = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new Command
                            {
                                Code              = "takeoff_command",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = true,
                                ResultIndifferent = true
                            }
                        };
                        takeoff.Vehicles.Add(vehicleToControl);
                        var takeoffCmd = messageExecutor.Submit <SendCommandResponse>(takeoff);
                        takeoffCmd.Wait();
                        Thread.Sleep(5000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "direct_vehicle_control":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleJoystickControl = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "direct_vehicle_control",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = true,
                                ResultIndifferent = true
                            }
                        };


                        vehicleJoystickControl.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listJoystickCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "roll":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "pitch":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "throttle":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "yaw":
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "pitch",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickCommands.Add(new CommandArgument
                                {
                                    Code  = "throttle",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }


                        vehicleJoystickControl.Command.Arguments.AddRange(listJoystickCommands);
                        var sendJoystickCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleJoystickControl);
                        sendJoystickCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "set_relative_heading":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleRelativeOffsetControl = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "set_relative_heading",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };


                        vehicleRelativeOffsetControl.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listRelativeOffsetCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "relative_heading":
                            listRelativeOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "relative_heading",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            break;
                        }

                        vehicleRelativeOffsetControl.Command.Arguments.AddRange(listRelativeOffsetCommands);
                        var sendRelativeOffsetCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleRelativeOffsetControl);
                        sendRelativeOffsetCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "set_position_offset":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        // Vehicle control in joystick mode
                        SendCommandRequest vehicleJoystickOffset = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "set_position_offset",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };


                        vehicleJoystickOffset.Vehicles.Add(vehicleToControl);

                        List <CommandArgument> listJoystickOffsetCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "x":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "y":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "z":
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "z",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "y",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listJoystickOffsetCommands.Add(new CommandArgument
                                {
                                    Code  = "x",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }


                        vehicleJoystickOffset.Command.Arguments.AddRange(listJoystickOffsetCommands);
                        var sendJoystickOffsetResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehicleJoystickOffset);
                        sendJoystickOffsetResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);

                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }


                    case "payload_control":
                    {
                        Console.Write("got command: {0}", commandName);
                        var commandArgs = result.ToString().Split(":")[1];
                        Console.Write("args of command: {0}", commandArgs);
                        SendCommandRequest vehiclePayloadCommandRequest = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "payload_control",
                                Subsystem         = Subsystem.S_CAMERA,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };
                        vehiclePayloadCommandRequest.Vehicles.Add(vehicleToControl);
                        List <CommandArgument> listPayloadCommands = new List <CommandArgument>();
                        var    directionCommand = commandArgs.ToString().Split(",")[0];
                        string commandValueStr  = commandArgs.ToString().Split(",")[1];
                        double commandValue     = double.Parse(commandValueStr,
                                                               System.Globalization.CultureInfo.InvariantCulture);

                        switch (directionCommand)
                        {
                        case "tilt":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "roll":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "zoom_level":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;

                        case "yaw":
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "yaw",
                                    Value = new Value()
                                    {
                                        DoubleValue = commandValue
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "tilt",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "roll",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            listPayloadCommands.Add(new CommandArgument
                                {
                                    Code  = "zoom_level",
                                    Value = new Value()
                                    {
                                        DoubleValue = 0
                                    }
                                });
                            break;
                        }

                        vehiclePayloadCommandRequest.Command.Arguments.AddRange(listPayloadCommands);
                        var sendPayloadCommandResponse =
                            messageExecutor.Submit <SendCommandResponse>(vehiclePayloadCommandRequest);
                        sendPayloadCommandResponse.Wait();
                        System.Console.WriteLine("Was sent {0}", commandValue);
                        Thread.Sleep(2000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "land_command":
                    {
                        SendCommandRequest land = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "land_command",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };
                        land.Vehicles.Add(vehicleToControl);
                        var landCmd = messageExecutor.Submit <SendCommandResponse>(land);
                        landCmd.Wait();
                        Thread.Sleep(5000);
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "joystick":
                    {
                        SendCommandRequest joystickModeCommand = new SendCommandRequest
                        {
                            ClientId = clientId,
                            Command  = new UGCS.Sdk.Protocol.Encoding.Command
                            {
                                Code              = "joystick",
                                Subsystem         = Subsystem.S_FLIGHT_CONTROLLER,
                                Silent            = false,
                                ResultIndifferent = false
                            }
                        };

                        joystickModeCommand.Vehicles.Add(vehicleToControl);
                        var joystickMode = messageExecutor.Submit <SendCommandResponse>(joystickModeCommand);
                        joystickMode.Wait();
                        ns.Write(ok, 0, ok.Length);
                        break;
                    }

                    case "manual":
                    {
                        break;
                    }
                    }
                }

                // System.Console.ReadKey();
                // tcpClient.Close();
                // messageSender.Cancel();
                // messageReceiver.Cancel();
                // messageExecutor.Close();
                // notificationListener.Dispose();
            }
        }