Close() public method

public Close ( int timeout ) : void
timeout int
return void
        public override void Insert(Person person)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(IPAddress.Parse("127.0.0.1"), 3180);

            NetworkStream networkStream = new NetworkStream(socket);

            string dataSend = extension + "|" + "Insert|" + person.ToXML();

            byte[] bytes = Encoding.UTF8.GetBytes(dataSend);
            networkStream.Write(bytes, 0, bytes.Length);

            bool isWork = true;
            while (isWork)
            {
                if (networkStream.DataAvailable)
                {
                    isWork = false;
                    byte[] buffer = new byte[socket.Available];
                    networkStream.Read(buffer, 0, buffer.Length);
                    string result = Encoding.UTF8.GetString(buffer);
                }
            }
            networkStream.Flush();
            networkStream.Close();
            socket.Close();
        }
 /// <summary>
 /// hungvv =======================Xoa ===========================
 /// </summary>
 private void DeleteData(string ID)
 {
     try
     {
         dh = new Entities.DonDatHang();
         cl = new Server_Client.Client();
         this.client = cl.Connect(Luu.IP, Luu.Ports);
         dh = new Entities.DonDatHang("Delete", ID);
         clientstrem = cl.SerializeObj(this.client, "DonDatHang", dh);
         int trave = 0;
         trave = System.Convert.ToInt32(cl.DeserializeHepper(clientstrem, trave));
         client.Close();
         clientstrem.Close();
         if (trave == 1)
         {
             SelectData();
             MessageBox.Show("Thành công !");
         }
         if (trave == 0)
         {
             MessageBox.Show("Thất bại !");
         }
     }
     catch (Exception)
     { }
 }
        public void Comunica2()
        {
            try
            {
                stream = client.GetStream();

                while (true)
                {

                    Byte[] byteStream = new byte[BUFFER_SIZE];

                    pegaTeclas();
                    write();
                    read(ref byteStream);

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                stream.Close();
                client.Close();
            }
        }
示例#4
0
        public bool SendCmdRequest(CmdRequest request)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect("127.0.0.1", Port);
                using (NetworkStream stream = new NetworkStream(socket))
                {
                    using (BsonWriter writer = new BsonWriter(stream))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Serialize(writer, request);
                        writer.Flush();
                        writer.Close();
                    }
                   
                    stream.Close();
                }
            }
            catch(Exception ex)
            {
                Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex);
                return false;
            }

            return true;
        }
示例#5
0
        /* PUBLIC VARS */
        /* CONSTRUCTOR */
        public ClientComm(Socket sock)
        {
            _Sock = sock;
            _Tp = new TextParser(); //has no constructor

            try
            {
                _Stream = new NetworkStream(_Sock);
                // precaches Plugins in constructor, if no plugin could be loaded -> Exception
                _Pm = new PluginManager();
                _Pm.LoadPlugins();
            }
            // PluginIns could not be loaded - quit!
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.Message);
                if (_Stream != null)
                { _Stream.Close(); }
                Console.WriteLine("Will quit now...");
                Console.WriteLine("---------------------");
                Console.ReadLine();
                Environment.Exit(1);
            }
            catch (Exception) { throw; }

            // if server quits, destroy objects
            System.AppDomain.CurrentDomain.ProcessExit += new EventHandler(ServerQuittingHandler);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(ServerQuittingHandler);
        }
示例#6
0
文件: Server.cs 项目: honux77/prostar
        static void Main(string[] args)
        {
            Console.Write("포트번호입력(1024 - 65535): ");
            int port = int.Parse(Console.ReadLine());
            IPEndPoint myAddr = new IPEndPoint(IPAddress.Any, port);
            Socket server = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);
            server.Bind(myAddr);

            server.Listen(10);
            Console.WriteLine("서버 시작");

            while (true)
            {
                Socket client = server.Accept();
                Console.WriteLine("클라이언트 {0} 접속",
                    client.RemoteEndPoint.ToString());
                NetworkStream ns = new NetworkStream(client);

                int len;
                string msg;
                while ((len = ns.Read(buf, 0, buf.Length)) != 0)
                {
                    msg = Encoding.UTF8.GetString(buf, 0, len);
                    Console.WriteLine("수신: {0}" , msg);
                    ns.Write(buf, 0, len);
                }
                Console.WriteLine("클라이언트 {0} 접속종료",
                    client.RemoteEndPoint.ToString());
                ns.Close();
                client.Close();
            }
        }
示例#7
0
 public static void Service()
 {
     while (true)
     {
         Socket soc = listener.AcceptSocket();
         try {
             Stream s = new NetworkStream(soc);
             StreamReader sr = new StreamReader(s);
             StreamWriter sw = new StreamWriter(s);
             sw.AutoFlush = true;
             sw.WriteLine("Send Message: ");
             while (true)
             {
                 string msg = sr.ReadLine();
                 if (msg == "" || msg == null) break;
                 Console.WriteLine(msg);
                 sw.WriteLine("Message received");
             }
             s.Close();
         }
         catch(Exception e){
             Console.WriteLine(e.Message);
         }
         soc.Close();
     }
 }
示例#8
0
        public void Start( CancellationToken token )
        {
            _newsock.Bind(_ipep);
            _newsock.Listen(10);

            Console.WriteLine("Waiting for a client...");

            var client = _newsock.Accept();
            var newclient = (IPEndPoint)client.RemoteEndPoint;

            Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port);

            using (var ns = new NetworkStream (client))
            {
                var mp = new TcpMultiplexer ();
                var capService = new CapService (mp);

                var rwStream = mp.CreateStream (CapName, TcpMultiplexer.Direction.InOut);

                var t1 = Task.Factory.StartNew (() => ReadAndAck (rwStream, CapName, token, capService));
                t1.Wait (token);

                Console.WriteLine ("Disconnected from {0}", newclient.Address);
                ns.Close ();
            }
        }
示例#9
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);
     }
 }
示例#10
0
        public static void DoIt(Socket acceptedSocket, List<string> messages)
        {
            Socket connectionSocket = acceptedSocket;

            Console.WriteLine("Server activated");

            Stream ns = new NetworkStream(connectionSocket);
            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);
            sw.AutoFlush = true; // enable automatic flushing

            messages.Add(sr.ReadLine());
            while (!String.IsNullOrEmpty(messages[messages.Count - 1]))
            {
                Console.WriteLine("Client: " + messages[messages.Count - 1]);
                try
                {
                    sw.WriteLine(StringToString(messages));
                    messages.Add(sr.ReadLine());
                }
                catch (IOException ex)
                {
                    Console.WriteLine("Exception !");
                    break;
                }
            }
            ns.Close();
            connectionSocket.Close();
        }
示例#11
0
        private void HandleRequest(object conSocket)
        {
            var connectionSocket = (Socket)conSocket;
            Stream ns = new NetworkStream(connectionSocket);
            var sr = new StreamReader(ns);
            var sw = new StreamWriter(ns);

            try
            {
                var line = "dummy";
                var requestRaw = "";
                while (line != "\r\n")
                {
                    line = sr.ReadLine() + "\r\n";
                    requestRaw += line;
                }

                var request = new HttpRequest(requestRaw);
                var response = new HttpResponse(request.Uri);

                StopServer = request.MessageType == "EXIT";

                var responseBytes = response.ToBytes();
                ns.Write(responseBytes, 0, responseBytes.Length);
            }
            finally
            {
                sw.Close();
                sr.Close();
                ns.Close();
                connectionSocket.Close();
            }
        }
    public void StopExchange()
    {
        exchangeStopRequested = true;

#if UNITY_EDITOR
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();

            stream         = null;
            exchangeThread = null;
        }
#else
        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            socket.Dispose();
            writer.Dispose();
            reader.Dispose();

            socket       = null;
            exchangeTask = null;
        }
#endif
        writer = null;
        reader = null;
    }
示例#13
0
        private void button1_Click(object sender, EventArgs e)
        {
            string s;
            myclient = new TcpClient(host, port);
            //get a Network stream from the server
            networkStream = myclient.GetStream();
            streamReader = new StreamReader(networkStream);
            streamWriter = new StreamWriter(networkStream);
            streamWriter.WriteLine("start,utilities," + passkey + "");
            label6.Text = "Sending Request";
            streamWriter.Flush();
            s = streamReader.ReadLine();
            streamReader.Close();
            streamWriter.Close();
            networkStream.Close();
            if (s == "success")
            {

                label6.Text = "Started SWG:ANH TC";
            }
            if (s == "fail")
            {
                label6.Text = "Failed to Start SWG:ANH TC";
            }
        }
示例#14
0
        public void getConnect()
        {
            Console.WriteLine("Trying to connect to the game server");
            try
            {
                clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 6000);
                stream = clientSocket.GetStream();

                byte[] messsage = Encoding.ASCII.GetBytes(common.parameters.JOIN);

                for (int i = 0; i < messsage.Length; i++)
                {
                    Console.WriteLine(messsage[i]);
                }

                stream.Write(messsage, 0, messsage.Length);

                stream.Flush();     //flush the stream
            }
            catch (Exception e)
            {
                Console.WriteLine("Initial connect to the server is Failed! Server is not started or connection is not stable");

                getConnect();
            }
            finally
            {
                if (stream != null && writer != null) {
                    stream.Close();     //close stream
                    writer.Close();
                    }
            }
        }
示例#15
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");
        }
示例#16
0
        public void sendNotify(string notify)
        {
            try
            {
                client.Connect(serverName, port);

                stream = client.GetStream();
                UnicodeEncoding encoder = new UnicodeEncoding();
                byte[] buffer = encoder.GetBytes(notify);

                stream.Write(buffer, 0, buffer.Length);

            }
            catch (SocketException ex)
            {
                Trace.TraceError(String.Format("unClientClass says: {0}", ex.Message));
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (client.Connected)
                {
                    client.Close();
                }
            }
        }
示例#17
0
 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint iep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),9000);
     s.Connect(iep);
     Console.WriteLine("Connected to Server...");
     NetworkStream ns=new NetworkStream(s);
     StreamReader sr=new StreamReader(ns);
     StreamWriter sw=new StreamWriter(ns);
     Console.WriteLine("Data From Server:{0}",sr.ReadLine());
     while(true)
     {
         string st;
         Console.Write("Nhap du  lieu gui len Server:");
         st=Console.ReadLine();
         sw.WriteLine(st);
         sw.Flush();
         if (st.ToUpper().Equals("QUIT"))
             break;
         Console.WriteLine("Du lieu tu Server la:{0}",sr.ReadLine());
     }
     sr.Close();
     sw.Close();
     ns.Close();
     s.Close();
 }
示例#18
0
        private void ServerListen()
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, localPort));
            serverSocket.Listen(1);

            while (true)
            {
                try
                {
                    Socket clientSocket = serverSocket.Accept();
                    using (NetworkStream stream = new NetworkStream(clientSocket))
                    {
                        var request = ReadRequest(stream);
                        OnNewCmdReceived(request);

                        stream.Close();
                    }

                    clientSocket.Close();
                }
                catch (Exception ex)
                {
                    Logger.AddError("Failed to process connection", ex);
                }
            }
        }
示例#19
0
        public void sendData(String message)
        {
            try {

                clientSocket = new TcpClient();

                clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 6000);
                if (clientSocket.Connected)
                {

                    stream = clientSocket.GetStream();

                    writer = new BinaryWriter(stream);
                    Byte[] tempMsg = Encoding.ASCII.GetBytes(message);

                    writer.Write(tempMsg);
                    Console.WriteLine("Data Sent- "+ message);
                    writer.Close();
                    stream.Close();

                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Communication (WRITING) Failed! due to "+ e.Message);
                sendData(message);
            }
            finally
            {
                clientSocket.Close();

            }
        }
示例#20
0
    public void CloseSocket()
    {
        exchangeStopRequested = true;
#if UNITY_EDITOR
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();
            stream         = null;
            exchangeThread = null;
        }
#endif
#if !UNITY_EDITOR
        Debug.Log("OnCloseSocket");
        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            writer.Dispose();
            reader.Dispose();
            socket.Dispose();
            socket       = null;
            exchangeTask = null;
        }
#endif
        connected = false;
        writer    = null;
        reader    = null;
    }
示例#21
0
 static void Main(string[] args)
 {
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9000);
     s.Bind(iep);
     s.Listen(10);
     Console.WriteLine("Waiting Client...");
     Socket sc = s.Accept();
     NetworkStream ns = new NetworkStream(sc);
     StreamReader sr = new StreamReader(ns);
     StreamWriter sw = new StreamWriter(ns);
     sw.WriteLine("Chao Client");
     sw.Flush();
     while (true)
     {
         string st;
         st = sr.ReadLine();
         Console.WriteLine("Client gui len:{0}",st);
         if (st.ToUpper().Equals("QUIT"))
             break;
         st = st.ToUpper();
         sw.WriteLine(st);
         sw.Flush();
     }
     sw.Close();
     sr.Close();
     ns.Close();
     sc.Close();
     s.Close();
 }
        public NetworkStream connect_sync()
        {
            try
            {
                ConnectionStatistics.numberOfConnections++;
                //Establish a connection to the node
                channel = new TcpClient();
                channel.Connect(node.GetEndPoint());

                //Get a stream to the node
                stream = channel.GetStream();
                ConnectionStatistics.numberOfConnections++;

                if(stream == null)
                {
                    ConnectionStatistics.missedConnections++;
                    channel.Close();
                    return null;
                }

                if(!stream.CanRead || !stream.CanWrite)
                {
                    ConnectionStatistics.noReadWritePermissions++;
                    stream.Close();
                    channel.Close();
                    return null;
                }
            }
            catch
            {
                return null;
            }
            return stream;
        }
 void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     while (true)
       {
     Socket socketForClient = tcpListener.AcceptSocket();
     if (socketForClient.Connected)
     {
       Write("Client connected");
       NetworkStream networkStream = new NetworkStream(socketForClient);
       System.IO.StreamWriter streamWriter =
     new System.IO.StreamWriter(networkStream);
       System.IO.StreamReader streamReader =
     new System.IO.StreamReader(networkStream);
       string theString = "Sending";
       streamWriter.WriteLine(theString);
       Write(theString);
       streamWriter.Flush();
       theString = streamReader.ReadLine();
       Write(theString);
       streamReader.Close();
       networkStream.Close();
       streamWriter.Close();
     }
     else
     {
       Write("Exiting...");
       break;
     }
     socketForClient.Close();
       }
 }
示例#24
0
        /// <summary>
        /// Recieve Dictionary of (string, object) that contains all info about recieved file 
        /// </summary>
        /// <param name="reciever">Socket of transfer</param>
        private void RecieveFileDict(Socket reciever)
        {
            NetworkStream netStream = new NetworkStream(reciever);

            byte[] data = new byte[1024];
            int dataCitit;
            int totalBytes = 0;
            List<byte> listOfDict = new List<byte>();
            while ((dataCitit = netStream.Read(data, 0, data.Length)) > 0)
            {
                listOfDict.AddRange(data);
                totalBytes += dataCitit;
            }

            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream(listOfDict.ToArray()))
            {
                this.contentOfAddingFile = (Dictionary<string, object>)bf.Deserialize(ms);
            }

            TestDisplay();

            DBWorker.SetValue(contentOfAddingFile);
            Console.WriteLine("Получено байт: {0}", totalBytes);
            netStream.Close();
        }
示例#25
0
        static void Main(string[] args)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                s.Connect("localhost", 25000);
            }
            catch (Exception ex)
            {
                Console.Write("Virhe: " + ex.Message);
                Console.ReadKey();
                return;
            }

            NetworkStream ns = new NetworkStream(s);

            StreamReader sr = new StreamReader(ns);
            StreamWriter sw = new StreamWriter(ns);

            Boolean on = true;

            while (on)
            {
                String viesti = "";
                viesti = sr.ReadLine();
                Console.WriteLine(viesti);
                String[] status = viesti.Split(' ');
                

                switch (status[0])
                {
                    case "220":
                        sw.WriteLine("HELO jyu.fi");
                        break;

                    case "221":
                        on = false;
                        break;

                    default:
                        Console.WriteLine("Virhe");
                        sw.WriteLine("QUIT");
                        break;
                } // switch
                sw.Flush();

            } // while


            Console.ReadKey();


            sw.Close();
            sr.Close();
            ns.Close();
            s.Close();


        }
示例#26
0
 public void EnviarDatos(string mensaje)
 {
     clientStream = client.GetStream();
     data = System.Text.Encoding.ASCII.GetBytes(mensaje);
     clientStream.Write(data, 0, data.Length);
     clientStream.Close();
 }
示例#27
0
        /// <summary>
        /// Communicate with SMTP server
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="from"></param>
        /// <param name="recipient"></param>
        /// <returns></returns>
        private Result WillAccept(string domain, string from, string recipient)
        {
            if (Email.ServerName == string.Empty)
            {
                throw new NullReferenceException("No Email.ServerName has been specified");
            }
            System.Net.Sockets.TcpClient client =
                new System.Net.Sockets.TcpClient(domain, (int)Port.Smtp);
            _stream = client.GetStream();
            _reader = new System.IO.StreamReader(client.GetStream());
            Result status     = Result.Succeeded;
            string mailServer = Email.ServerName;
            string crlf       = Environment.NewLine;

            if (mailServer == null)
            {
                mailServer = MxRecord.Infer(from).HostName;
            }

            // some servers acknowledge connection
            if (_reader.Peek() != -1)
            {
                this.ValidResponse(Response.ConnectSuccess);
            }

            // HELO
            if (!this.SmtpCommand(string.Format("HELO {0}{1}", mailServer, crlf)))
            {
                status = Result.NoServerGreeting;
            }
            // MAIL FROM
            if (status.Contains(Result.Succeeded) &&
                !this.SmtpCommand(string.Format("MAIL FROM:<{0}>{1}", from, crlf)))
            {
                status = Result.RefusedMailFrom;
            }
            // RCPT TO
            if (status.Contains(Result.Succeeded) &&
                !this.SmtpCommand(string.Format("RCPT TO:<{0}>{1}", recipient, crlf)))
            {
                status = Result.AddressNotFound;
            }
            // RCPT TO random
            // if random address is successful then server is not really validating
            if (status.Contains(Result.Succeeded) &&
                this.SmtpCommand(string.Format("RCPT TO:<{0}@{1}>{2}", _random,
                                               this.HostPart(recipient), crlf)))
            {
                status = Result.ValidatedBadAddress;
            }
            // QUIT
            this.SmtpCommand(string.Format("QUIT{0}", crlf), Response.QuitSuccess);

            _stream.Close();
            _reader.Close();
            client.Close();

            return(status);
        }
示例#28
0
		public void Close(ref TcpClient clientSocket, ref NetworkStream networkStream)
		{
			networkStream.Close();
			clientSocket.Client.Close();
			clientSocket.Close();

			networkStream = null;
			clientSocket = null;
		}
示例#29
0
        public static void receiveData()
        {
            try
            {
                //Creating listening Socket
                listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 7000);
                Console.WriteLine("Waiting for server response");

                //Starts listening
                listener.Start();
                //Establish connection upon server request
                while (true)
                {

                    socket = listener.AcceptSocket();

                    Console.WriteLine("Connetion is established");

                    //Fetch the messages from the server
                    int asw = 0;
                    int count = 2;
                    //create a network stream using connecion
                    NetworkStream serverStream = new NetworkStream(socket);
                    List<Byte> inputStr = new List<byte>();

                    //fetch messages from  server
                    while (asw != -1)
                    {
                        count++;
                        asw = serverStream.ReadByte();
                        inputStr.Add((Byte)asw);
                    }

                    String messageFromServer = Encoding.UTF8.GetString(inputStr.ToArray());

                    Console.WriteLine("Response from server to join ");

                    torkenizer.tokenizeMessage(messageFromServer);
                    Console.WriteLine(messageFromServer);
                    serverStream.Close();       //close the netork stream

                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Communication (RECEIVING) Failed! \n " + e.StackTrace);
                error= true;
            }
            finally
            {
                if (socket != null)
                    if (socket.Connected)
                        socket.Close();
                if (error)
                   receiveData();
            }
        }
 public void AsyncProcessResponse (IServerResponseChannelSinkStack sinkStack, object state,
                                   IMessage msg, ITransportHeaders headers, Stream responseStream)
 {
     ClientConnection connection = (ClientConnection)state;
     NetworkStream stream = new NetworkStream (connection.Client);
     UnixMessageIO.SendMessageStream (stream, responseStream, headers, connection.Buffer);
     stream.Flush ();
     stream.Close ();
 }
示例#31
0
        private void loginButton_Click(object sender, EventArgs e)
        {
            string host = IPTextBox.Text;
            int port; //TODO: try parse direito cuz errors no if
            string name = NickTextBox.Text;
            int nrBytes = 0;

            if(host == "" || name == "" || portTextBox.Text == "0" || !Int32.TryParse(portTextBox.Text, out port))
            {
                MessageBox.Show("Please fill Host and/or Username.");
                return;
            }

            try
            {
                client = new TcpClient(host, port);
            }
            catch(Exception)
            {
                MessageBox.Show("Error connecting to server.");
                return;
            }

            stream = client.GetStream();

            //enviar pedido de autenticação (nome)
            stream.WriteByte(GameForm.renameByte);
            byte[] bfr = Encoding.ASCII.GetBytes(name);
            stream.Write(bfr, 0, bfr.Length);
            stream.WriteByte((byte)'\n');

            //receber resposta
            string msg = "";
            do
            {
                nrBytes = stream.Read(bfr, 0, bfr.Length);
                msg += Encoding.ASCII.GetString(bfr, 0, nrBytes);
            } while (!msg.Contains("\n"));

            if(msg.StartsWith(GameForm.loginAprovedString))
            {
                new GameForm(client, this).Show();
                this.Hide();
            }
            else
            {
                if (msg.StartsWith(GameForm.errorString + "0"))
                    MessageBox.Show("That name is already in use!");
                else if (msg.StartsWith(GameForm.errorString + "1"))
                    MessageBox.Show("Server Full!");
                else
                    MessageBox.Show("Server dont like you!");
                stream.Close();
                client.Close();
            }
        }
示例#32
0
 public static void TcpClose(NetworkStream stream)
 {
     lock (_clients)
     {
         stream.Close();
         var c = _clients[stream];
         c.Close();
         _clients.Remove(stream);
     }
 }
示例#33
0
 /// <summary>
 /// Close stream.
 /// </summary>
 public void Close()
 {
     if (!close)
     {
         sw.Dispose();
         sr.Dispose();
         ns.Close();
         close = true;
     }
 }
示例#34
0
        public static void Main(string[] args)
        {
            int port = int.Parse (args [0]);
            TcpListener listener = new TcpListener (IPAddress.Any, port);

            while (true) {

                try {
                    listener.Start ();
                } catch {
                    return;
                }

                using (Socket socket = listener.AcceptSocket ()) {
                    using (NetworkStream stream = new NetworkStream (socket)) {
                        using (StreamReader rdr = new StreamReader (stream)) {
                            while (true) {
                                string cmd = rdr.ReadLine ();

                                if (string.IsNullOrEmpty (cmd)) {
                                    rdr.Close ();
                                    stream.Close ();
                                    listener.Stop ();
                                    return;
                                }

                                if (string.IsNullOrWhiteSpace (cmd))
                                    continue;

                                string[] split = cmd.Trim ().Split (' ');
                                string filename = split.First ();
                                string arg = string.Join (" ", split.Skip (1));

                                try {
                                    Process prc = new Process ();
                                    prc.StartInfo = new ProcessStartInfo ();
                                    prc.StartInfo.FileName = filename;
                                    prc.StartInfo.Arguments = arg;
                                    prc.StartInfo.UseShellExecute = false;
                                    prc.StartInfo.RedirectStandardOutput = true;
                                    prc.Start ();
                                    prc.StandardOutput.BaseStream.CopyTo (stream);
                                    prc.WaitForExit ();
                                } catch {
                                    string error = "Error running command " + cmd + "\n";
                                    byte[] errorBytes = Encoding.ASCII.GetBytes (error);
                                    stream.Write (errorBytes, 0, errorBytes.Length);
                                }
                            }
                        }
                    }
                }
            }
        }
示例#35
0
        /// <summary>
        /// Send the raw text data to router by socket.
        /// </summary>
        /// <param name="text">raw text to be sent</param>
        /// <returns>Send result</returns>
        private bool Send(string text)
        {
            //UnityEngine.Debug.Log ("Sending raw text to router: " + text);

            if (_clientSocket == null)
            {
                return(false);
            }

            lock (_clientSocket)
            {
                //UnityEngine.Debug.Log ("Are we even connected, we need to be connected to send something right...");
                if (!_clientSocket.Connected)
                {
                    UnityEngine.Debug.Log("We're not connected OMG!");
                    _isEstablished = false;
                    _clientSocket  = null;
                    return(false);
                }
                else
                {
                    //UnityEngine.Debug.Log ("Seems we're connected...");


                    try
                    {
                        System.IO.Stream       s  = new System.Net.Sockets.NetworkStream(_clientSocket);
                        System.IO.StreamReader sr = new System.IO.StreamReader(s);
                        System.IO.StreamWriter sw = new System.IO.StreamWriter(s);

                        sw.Write(text);
                        sw.Flush();

                        //byte[] byteArr = Encoding.UTF8.GetBytes(message);
                        //this.socket.Send(byteArr);
                        sr.Close();
                        sw.Close();
                        s.Close();

                        //UnityEngine.Debug.Log ("OCNetworkElement::Send was succesful!");
                    }
                    catch (System.Exception e)
                    {
                        UnityEngine.Debug.Log("Something went wrong in OCNetworkElement::Send: " + e.Message);
                        return(false);
                    }
                }
            }
            return(true);
        }
    public void DisconnectFromServer()
    {
        print("Disconnect form Server");

        if (ns != null)
        {
            byte[] ba = new byte[] { 0x65, 0x6e, 0x64 };//System.Text.Encoding.Unicode.GetBytes ("end");
            ns.Write(ba, 0, ba.Length);
            ns.Flush();
            //閉じる
            ns.Close();
            tcp.Close();
        }

        isConnectedToServer = false;
    }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ServerThread != null && ServerThread.IsAlive)
            {
                ns.Close();
                client.Close();
                listener.Stop();
                ServerThread.Abort();
                UnityProcess.Kill();
                UnityProcess.Close();
                UnityProcess.Dispose();
            }

            stop     = true;
            e.Cancel = Stop.Enabled;
            closing  = true;
        }
示例#38
0
    public void CloseSocket()
    {
        exchangeStopRequested = true;
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();
            stream         = null;
            exchangeThread = null;
        }

        IsConnected = false;
        writer      = null;
        reader      = null;
    }
示例#39
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();
    }
示例#40
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            AccurateTimer.Stop();
            if (inputThread != null && inputThread.IsAlive)
            {
                inputThread.Abort();
                SerialObj.Close();
            }

            if (ServerThread != null && ServerThread.IsAlive)
            {
                ns.Close();
                client.Close();
                listener.Stop();
                ServerThread.Abort();
                UnityProcess.Kill();
                UnityProcess.Close();
                UnityProcess.Dispose();
            }
        }
示例#41
0
        /// <summary>
        /// Close the connection and release all resources.
        /// </summary>
        private void CloseEx()
        {
            try
            {
                if (_socket != null)
                {
                    _socket.Shutdown(SocketShutdown.Both);
                }
            }
            catch { }

            try
            {
                if (_socket != null)
                {
                    _socket.Disconnect(false);
                }
            }
            catch { }

            try
            {
                if (_socket != null)
                {
                    _socket.Close();
                }

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

                if (_networkStream != null)
                {
                    _networkStream.Close();
                }
            }
            catch { }
        }
示例#42
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();
        }
示例#43
0
        public async Task ServerConnect()
        {
            //int port = 3333;
            //ListenするIPアドレス
            string ipString = "127.0.0.1";

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

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

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

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

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

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); System.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();

            //読み取り、書き込みのタイムアウトを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;
                    System.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');
            System.Console.WriteLine(resMsg);

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

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

            //リスナを閉じる
            listener.Stop();
            System.Console.WriteLine("Listenerを閉じました。");

            System.Console.ReadLine();
        }
示例#44
0
        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            f.Navigate(sa);
            TcpClient tcp = new TcpClient(ipaddress, 2001);

            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);
            ns = tcp.GetStream();


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

            //サーバーから送られたデータを受信する


            await Task.Run(async() =>
            {
                while (true)
                {
                    string resMsg = await resGetAsync();
                    status_update(resMsg);
                    if (resMsg.IndexOf("全員") > -1)
                    {
                        break;
                    }
                    await Task.Delay(100);
                }
                //ゲームスタート!!
                //Get namelist
                while (true)
                {
                    string temp = await resGetAsync();
                    if (temp.IndexOf("namelist[") > -1)
                    {
                        Console.WriteLine(temp);
                        int i = 0;
                        MatchCollection mc = Regex.Matches(temp, @"\{(.+?)\}", RegexOptions.Singleline);
                        foreach (Match m in mc)
                        {
                            string tem    = m.ToString().Replace("{", "").Replace("}", "").Replace("\r\n", "").Replace("\n", "");
                            namelist[i++] = tem;
                        }
                        break;
                    }
                    await Task.Delay(100);
                }
                int cnt = 0;
                foreach (string s in namelist)
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        if (s != name)
                        {
                            if (cnt == 0)
                            {
                                name1.Name = s;
                                name1.Text = s + "[0]";
                            }
                            else if (cnt == 1)
                            {
                                name2.Name = s;
                                name2.Text = s + "[0]";
                            }
                            else
                            {
                                name3.Name = s;
                                name3.Text = s + "[0]";
                            }
                            cnt++;
                        }
                        else
                        {
                            name_me.Name = name;
                            name_me.Text = name + "[0]";
                        }
                    });
                }
                await this.Dispatcher.Invoke(async() =>
                {
                    sa.status.Text = "読み込んでいます";

                    for (int i = 1; i <= 13; i++)
                    {
                        clover[i - 1] = new BitmapImage();
                        clover[i - 1].BeginInit();
                        clover[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\clover\" + i.ToString() + ".png");
                        clover[i - 1].EndInit();
                    }
                    for (int i = 1; i <= 13; i++)
                    {
                        heart[i - 1] = new BitmapImage();
                        heart[i - 1].BeginInit();
                        heart[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\heart\" + i.ToString() + ".png");
                        heart[i - 1].EndInit();
                    }
                    for (int i = 1; i <= 13; i++)
                    {
                        spade[i - 1] = new BitmapImage();
                        spade[i - 1].BeginInit();
                        spade[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\spade\" + i.ToString() + ".png");
                        spade[i - 1].EndInit();
                    }
                    for (int i = 1; i <= 13; i++)
                    {
                        dia[i - 1] = new BitmapImage();
                        dia[i - 1].BeginInit();
                        dia[i - 1].UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\dia\" + i.ToString() + ".png");
                        dia[i - 1].EndInit();
                    }
                    joker.BeginInit();
                    joker.UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\joker.png");
                    joker.EndInit();
                    back.BeginInit();
                    back.UriSource = new Uri(System.IO.Path.GetDirectoryName(Application.ResourceAssembly.Location) + @"\tramp\back.jpg");
                    back.EndInit();
                    await Task.Delay(1500);
                    sa.status.Text = "ゲーム開始を待機しています";
                    sendMes("OKREADY");
                    //ゲーム開始を待機する
                    string temp = await resGetAsync();
                    while (true)
                    {
                        if (temp.IndexOf("gamestart") > -1)
                        {
                            break;
                        }
                        await Task.Delay(500);
                    }
                    //カードを初期化
                    for (int i = 0; i < 14; i++)
                    {
                        mycardV[i] = -1;
                    }
                    //カード情報をゲット
                    while (true)
                    {
                        if (temp.IndexOf("cardinfo") > -1)
                        {
                            mycard = temp;
                            MatchCollection kmc = Regex.Matches(temp, @"\[(.+?)\]");
                            MatchCollection vmc = Regex.Matches(temp, @"\{(.+?)\}");
                            int mCnt            = 0;
                            int mmCnt           = 0;
                            foreach (Match m in kmc)
                            {
                                foreach (Match mm in vmc)
                                {
                                    if (mCnt == mmCnt)
                                    {
                                        string ms  = m.ToString().Replace("[", "").Replace("]", "");
                                        string mms = mm.ToString().Replace("{", "").Replace("}", "");
                                        Console.WriteLine(ms + mms);
                                        mycardK[mCnt] = ms;
                                        mycardV[mCnt] = int.Parse(mms);
                                    }
                                    mmCnt++;
                                }

                                mmCnt = 0;
                                mCnt++;
                            }
                            mycardR = mCnt;
                            break;
                        }

                        await Task.Delay(500);
                        temp = await resGetAsync();
                    }

                    {
                        Image img  = new Image();
                        img.Source = back;
                        img.Width  = 28;
                        img.Height = 100;
                        sp1.Children.Add(img);
                    }

                    {
                        Image img  = new Image();
                        img.Source = back;
                        img.Width  = 28;
                        img.Height = 100;
                        sp2.Children.Add(img);
                    }

                    {
                        Image img  = new Image();
                        img.Source = back;
                        img.Width  = 28;
                        img.Height = 100;
                        sp3.Children.Add(img);
                    }
                    status.Text = "";
                });
                while (true)
                {
                    updateCard();
                    await Task.Delay(1000);//カードを更新してゲームを進行していきます
                }
            });

            //閉じる
            ns.Close();
            tcp.Close();
            Console.WriteLine("切断しました。");
        }
示例#45
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;
            }
        }
示例#46
0
        private void PlayStream(string url, int offset)
        {
            if (url.Substring(0, 7).ToLower().CompareTo("plex://") == 0)
            {
                _isWebkit = url.Contains("webkit");

                Uri uri = new Uri(url);

                url = uri.Query.Split(new char[] { '&' })[0];
                url = url.Substring(5);
                url = HttpUtility.UrlDecode(url);

                //
                // special case for Netflix plugin
                //

                if (url.IndexOf("netflix") != -1)
                {
                    string[] parts = url.Split(new char[] { '&' });

                    string tmp = parts[0];

                    if (url.IndexOf("#resume") != -1)
                    {
                        tmp += "#resume";
                    }
                    else
                    {
                        tmp += "#restart";
                    }

                    url = tmp;

                    //
                    // end case
                    //
                }

                Clipboard.SetText(url);

                //
                // prototype RTMP support
                //
                //if (url.IndexOf("http://www.plexapp.com/player/player.php?url=") != -1)
                //{
                //    url = Uri.UnescapeDataString(url.Substring(url.IndexOf("=") + 1));
                //    PlayHttpWithDirectShow(url);
                //    return;
                //}

                if (url.IndexOf("hulu") != -1)
                {
                    _isWebkit   = true;
                    _identifier = "com.plex.plugins.hulu";

                    OpenWebPage(url);
                    return;
                }

                OpenWebPage(url);

                return;
            }
            else
            {
                if (url.IndexOf("/video") != -1)
                {
                    if (!url.Contains(":") || url.LastIndexOf(":") > 5)
                    {
                        url = url.Substring(url.IndexOf("/video"));

                        System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                        client.Connect(Properties.Settings.Default.Server, 32400);

                        System.Net.Sockets.NetworkStream ns = client.GetStream();
                        StreamWriter w = new StreamWriter(ns);
                        StreamReader r = new StreamReader(ns);

                        w.WriteLine("GET " + url + " HTTP/1.0");

                        if (_useAuth == true)
                        {
                            w.WriteLine("X-Plex-User: "******"X-Plex-Pass: "******"";

                        while (s != null)
                        {
                            if (s.ToLower().IndexOf("http://") != -1)
                            {
                                newURL = s.Substring(s.IndexOf("http://"));

                                r.Close();
                                w.Close();
                                ns.Close();
                                client.Close();

//                                PlayTranscodedWithSegments(url);
                                PlayHttpWithDirectShow(newURL);

                                break;
                            }

                            if (s.ToLower().IndexOf("plex://") != -1)
                            {
                                newURL = s.Substring(s.IndexOf("plex://"));

                                r.Close();
                                w.Close();
                                ns.Close();
                                client.Close();

                                PlayStream(newURL, offset);
                                break;
                            }

                            s = r.ReadLine();
                        }

                        return;
                    }
                }

                if (url.Contains(FQDN()) == true)
                {
                    if (url.Contains("plugin"))
                    {
                        _playbackType = Enums.PlaybackType.UseFFPlayStream;
                    }
                    else
                    {
                        _playbackType = (Enums.PlaybackType)Properties.Settings.Default.PlaybackMode;
                    }

                    switch (_playbackType)
                    {
                    case Enums.PlaybackType.UseFFPlayDirect:
                        PlayHttpWithDirectShow(url);
                        break;

                    case Enums.PlaybackType.UseOtherMP:
                        string setWatchedURL = FQDN() + "/:/scrobble?key=" + _currentRatingKey + "&identifier=com.plexapp.plugins.library";
                        SetWatchedStatus(setWatchedURL);
                        PlayHttpStreamWithOtherMP(url);
                        break;

                    case Enums.PlaybackType.UseFFPlayStream:
                        PlayTranscodedWithSegments(url);
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    PlayHttpWithDirectShow(url);
                }
            }
        }
示例#47
0
        public async Task ClientConnect()
        {
            //サーバーに送信するデータを入力してもらう
            //System.Console.WriteLine("文字列を入力し、Enterキーを押してください。");
            string sendMsg = "heliiw";//System.Console.ReadLine();

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


            //try
            //{
            //TcpClientを作成し、サーバーと接続する
            System.Net.Sockets.TcpClient tcp = await Task.Run(() => new System.Net.Sockets.TcpClient(ipOrHost, port));

            System.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);

            //}
            //catch (IOException e)
            //{
            //    System.Console.WriteLine("文字列を入力し、Enterキーを押してください。" + e);
            //}

            //catch (IOException e)
            //{
            //    System.Console.WriteLine("文字列を入力し、Enterキーを押してください。"+e);
            //}



            //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);
            System.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)
                {
                    System.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');
            System.Console.WriteLine(resMsg);

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

            System.Console.ReadLine();
            //return "message1";
        }
示例#48
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();
    }
示例#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("切断しました。");
        }
    }
示例#50
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();
    }
示例#51
0
        private void button1_Click(object sender, EventArgs e)
        {
            // サーバーのIPアドレス(または、ホスト名)とポート番号
            string ipOrHost = "127.0.0.1";
            //            long ipOrHost = "127.0.0.1";
            int port = 1024;

            byte[] byteIpAddress  = { 192, 168, 1, 6 };
            byte[] localIpAddress = { 192, 168, 1, 6 };

            try
            {
                //            System.Net.IPAddress ipAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0];
                System.Net.IPAddress ipAddress  = new System.Net.IPAddress(byteIpAddress);
                System.Net.IPAddress ipAddress2 = new System.Net.IPAddress(localIpAddress);

                System.Net.IPEndPoint        ipLocalEndPoint = new System.Net.IPEndPoint(ipAddress2, 60000);
                System.Net.IPEndPoint        ipRemotePoint   = new System.Net.IPEndPoint(ipAddress, 1024);
                System.Net.Sockets.TcpClient tcpClientA      = new System.Net.Sockets.TcpClient(ipLocalEndPoint);
                tcpClientA.Connect(ipRemotePoint);
                //            tcpClientA.Connect(ipLocalEndPoint);

                //            System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port);
                //            System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient(ipOrHost, port);

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

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


                string sendMsg = this.textBox1.Text;

                // サーバーにデータを送信する
                // 文字列をbyte型配列に変換
                System.Text.Encoding enc = System.Text.Encoding.UTF8;

                //            byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                //            byte[] sendBytes = { 0x01, 0x02, 0x03, 0x04 };

                byte[] sendBytes = new byte[sendMsg.Length];

                for (int i = 0; i < sendMsg.Length; i++)
                {
                    sendBytes[i] = (byte)sendMsg[i];
                }

                sendBytes[0] = 0x00;
                sendBytes[1] = 0x01;

                byte[] buf = Encoding.ASCII.GetBytes(sendMsg);

                byte[] buf2 = FromHexString(sendMsg);;
                //            buf2[0] = BitConverter.ToSingle(buf[0], 0);

                // データを送信する
                //            ns.Write(sendBytes, 0, sendBytes.Length);
                ns.Write(buf2, 0, buf2.Length);


                // コミットテスト

                // 閉じる
                ns.Close();
                //            tcp.Close();
                tcpClientA.Close();
            }
            catch (Exception)
            {
                textBox1.Text = "エラーが発生しました";
            }
            finally
            {
            }
        }
示例#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();
    }
示例#53
0
    private static void Send()
    {
        // サーバに送信するデータを入力してもらう
        Console.WriteLine("文字列を入力し,Enterキーを押して下さい.");
        string sendMsg = String.Format("{0}", count);

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

        // サーバのIPアドレスとポート番号
        string ipOrHost = "127.0.0.1";
        // strinb ipOrHost = "localhost";
        int port = 50000;

        // 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();

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

        // サーバから送られたデータを受信する
        // 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);
        // } 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("切断しました.");
    }
示例#54
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();
    }
示例#55
0
        /// <summary>
        /// Send the raw text data to router by socket.
        /// </summary>
        /// <param name="text">raw text to be sent</param>
        /// <returns>Send result</returns>
        private bool Send(string text)
        {
            //UnityEngine.Debug.Log ("Sending raw text to router: " + text);

            if (_clientSocket == null)
            {
                return(false);
            }

            lock (_clientSocket)
            {
                //FIXME [RACE]: I want to describe a race condition whereby, SOMETIMES
                // by having Disconnect print it is disconnecting, I slowed down execution enough that Send() does not fire off
                // the erroneously proced error message that we disconnected midSend (while the whole game is shutting down).
                //obviously this is not ideal at all, but I have documented it here.

                //SO! I am trying out ways to make sure 'LogError' doesn't run IF the game is shutting down.
                //enabled didn't work. _isEstablished may be too much- but it DOES seem to work. I will keep the FixMe around
                //a little longer...

                if (!this._isEstablished)
                {
                    UnityEngine.Debug.Log(OCLogSymbol.CONNECTION + "OCNetworkElement is shutting down; not sending message.");
                    _isEstablished = false;
                    _clientSocket  = null;
                    return(false);
                }

                //UnityEngine.Debug.Log ("Are we even connected, we need to be connected to send something right...");
                if (!_clientSocket.Connected)
                {
                    UnityEngine.Debug.LogError(OCLogSymbol.ERROR + "We lost connection while sending!");
                    _isEstablished = false;
                    _clientSocket  = null;
                    return(false);
                }
                //else
                //UnityEngine.Debug.Log ("Seems we're connected...");

                //TODO: Delete this, I'm using it as a reference

                /*bool canSend = true;
                 * while(canSend)
                 * {
                 *      if(!_clientSocket.Pending())
                 *      {
                 *              //UnityEngine.Debug.Log (System.DateTime.Now.ToString ("HH:mm:ss.fff") + ": Nope, not pending...");
                 *              if (_shouldStop)
                 *                      UnityEngine.Debug.LogError(OCLogSymbol.IMPOSSIBLE_ERROR + "OCServerListener.Listener() has TCPListener.Pending() reporting false. Which is funny, because IT SHOULDN'T BE HERE BECAUSE _shouldStop IS TRUE!!");
                 *              // If listener is not pending, sleep for a while to relax the CPU.
                 *              yield return new UnityEngine.WaitForSeconds(0.5f);
                 *      }
                 */

                try
                {
                    System.IO.Stream       s  = new System.Net.Sockets.NetworkStream(_clientSocket);
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(s);

                    sw.Write(text);
                    sw.Flush();

                    //byte[] byteArr = Encoding.UTF8.GetBytes(message);
                    //this.socket.Send(byteArr);

                    sw.Close();
                    s.Close();

                    //UnityEngine.Debug.Log ("OCNetworkElement::Send was succesful!");
                }
                catch (System.Exception e)
                {
                    UnityEngine.Debug.LogError(OCLogSymbol.ERROR + "Something went wrong in OCNetworkElement::Send: " + e.Message);
                    return(false);
                }
            }
            return(true);
        }
示例#56
0
        /// <summary>
        /// 发送单个文件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="task"></param>
        /// <param name="item"></param>
        void PerformSendFile(TcpClient client, FileTaskInfo task, FileTaskItem item)
        {
            System.IO.FileStream             fs     = null;
            System.Net.Sockets.NetworkStream writer = null;
            try
            {
                writer = client.GetStream();
            }
            catch (Exception)
            {
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                return;
            }
            try
            {
                fs = new System.IO.FileStream(item.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            }
            catch (Exception)
            {
                if (writer != null)
                {
                    writer.Close();
                }
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                OnFileSystemOperationError(new FileSystemOperationErrorEventArgs(FileSystemOperationType.OpenFileToSend, item.FullPath, task.RemoteHost));

                return;
            }
            using (fs)
            {
                //检测断点数据是否正确
                if (item.CurrentFileTransfered < 0 || item.CurrentFileTransfered > (ulong)fs.Length)
                {
                    item.CurrentFileTransfered = 0;
                }
                fs.Seek((long)item.CurrentFileTransfered, System.IO.SeekOrigin.Begin);

                //设置当前任务信息
                item.CurrentFileSize = (ulong)fs.Length;
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Processing);
                item.StartTime = DateTime.Now;

                using (writer)
                {
                    byte[] buffer = new byte[SendBuffer];                       //缓冲区

                    while (item.CurrentFileTransfered < item.CurrentFileSize)
                    {
                        int bytesRead = fs.Read(buffer, 0, buffer.Length);
                        try
                        {
                            writer.Write(buffer, 0, bytesRead);
                        }
                        catch (Exception)
                        {
                            TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                            break;
                        }

                        //更新进度
                        item.CurrentFileTransfered += (ulong)bytesRead;
                        item.FinishedSize          += (ulong)bytesRead;
                    }
                    item.FinishedFileCount++;
                    writer.Close();
                }
                fs.Close();
                //标记任务完成
                if (item.State != FileTaskItemState.Failure)
                {
                    TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Finished);
                }
            }
        }
        /// <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());
        }
示例#58
0
        protected virtual void OnFileSystemOperationError(FileSystemOperationErrorEventArgs e)
        {
            if (FileSystemOperationError == null)
            {
                return;
            }

            if (!IPMClient.NeedPostMessage)
            {
                FileSystemOperationError(this, e);
            }
            else
            {
                if (scpcFileSystemOperationError == null)
                {
                    scpcFileSystemOperationError = (s) => { FileSystemOperationError(this, s as FileSystemOperationErrorEventArgs); }
                }
                ;
                IPMClient.SendASynchronizeMessage(scpcFileSystemOperationError, e);
            }
        }

        #region 发送文件事件



        #endregion


        #endregion

        #region 发送文件-监听线程

        /// <summary>
        /// 开始发送文件的监听线程
        /// </summary>
        void StartListener()
        {
            System.Threading.ThreadStart ts = ListenForSendRequest;
            new System.Threading.Thread(ts)
            {
                IsBackground = true
            }.Start();
        }

        /// <summary>
        /// 关闭监听线程
        /// </summary>
        void CloseListener()
        {
            listener.Stop();
            IsInitialized = false;
        }

        /// <summary>
        /// 监听函数
        /// </summary>
        void ListenForSendRequest()
        {
            listener.Start();
            while (IsInitialized)
            {
                try
                {
                    TcpClient client = listener.AcceptTcpClient();
                    //开始发送线程
                    if (client != null)
                    {
                        System.Diagnostics.Debug.WriteLine("文件发送线程:已经接收到连接请求,远程IP:" + client.Client.RemoteEndPoint.ToString());

                        new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(PerformFileSend))
                        {
                            IsBackground = true
                        }.Start(client);
                    }
                }
                catch (Exception)
                {
                    if (!IsInitialized)
                    {
                        break;
                    }
                }
            }
        }

        #endregion
        #region 发送文件-发送线程

        /// <summary>
        /// 处理文件发送请求
        /// </summary>
        /// <param name="client"></param>
        void PerformFileSend(object p)
        {
            System.Diagnostics.Debug.WriteLine("文件发送线程 [0x" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString("X4") + "] 已经启动");

            using (TcpClient client = p as TcpClient)
            {
                byte[] buffer        = new byte[400];                                  //接收或发送缓冲区
                int    bytesReceived = ReceiveByBuffer(client, buffer, buffer.Length); //第一步:接收文件传输命令

                if (bytesReceived < 1)
                {
                    return;                                                   //没收到数据
                }
                Message request = ParseSendCommand(buffer, 0, bytesReceived); //试着解析命令
                System.Diagnostics.Debug.WriteLineIf(request == null, "未能解析收到的请求,退出发送线程");

                if (request == null)
                {
                    return;
                }
                System.Diagnostics.Debug.WriteLine("已解析文件请求:" + request.NormalMsg.ToString());

                //非法请求
                //查找任务
                string[] taskInfo = request.NormalMsg.Split(':');
                ulong    pid      = 0ul;
                int      tid      = 0;

                FileTaskItem task = null;
                if (taskInfo.Length < 2 ||
                    !ulong.TryParse(taskInfo[0], System.Globalization.NumberStyles.AllowHexSpecifier, null, out pid) ||
                    !int.TryParse(taskInfo[1], System.Globalization.NumberStyles.AllowHexSpecifier, null, out tid) ||
                    (task = TaskManager.QuerySendTask(pid, tid, (client.Client.RemoteEndPoint as IPEndPoint).Address)) == null
                    )
                {
                    return;
                }
                System.Diagnostics.Debug.WriteLine(string.Format("文件请求已经接纳,文件编号:0x{0:x8},文件索引:0x{1:x4}", pid, tid));

                TaskManager.MarkSendTaskItemState(task, FileTaskItemState.Initializing);
                //准备发送
                if (task.IsFolder)
                {
                    PerformSendDirectory(client, task.TaskInfo, task);
                }
                else
                {
                    //文件支持有限的断点续传
                    if (taskInfo.Length == 3)
                    {
                        ulong temp;
                        if (ulong.TryParse(taskInfo[2], out temp))
                        {
                            task.CurrentFileTransfered = temp;
                            task.FileTransferedAtPast  = temp;
                        }
                        System.Diagnostics.Debug.WriteLineIf(task.CurrentFileTransfered > 0, string.Format("断点模式,从 0x{0} 处开始续传", task.CurrentFileTransfered));
                    }

                    PerformSendFile(client, task.TaskInfo, task);
                }
                client.Close();
            }
        }

        //发送文件夹
        void PerformSendDirectory(TcpClient client, FileTaskInfo task, FileTaskItem item)
        {
            NetworkStream stream = null;

            try
            {
                stream = client.GetStream();
            }
            catch (Exception)
            {
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                return;
            }

            string         currentDirectory = item.FullPath;                    //当前处理路径
            Stack <string> directoryStack   = new Stack <string>();             //文件夹栈

            directoryStack.Push("");

            bool needUpdateTotal = item.TotalSize == 0;                         //是否需要在发送的时候更新统计

            TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Processing);
            item.StartTime = DateTime.Now;

            using (stream)
            {
                while (!string.IsNullOrEmpty(currentDirectory) || directoryStack.Count > 0)
                {
                    if (!PerformSendDirectory_SendCreateDirCommand(currentDirectory, stream, task, item))
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(currentDirectory))
                    {
                        if (directoryStack.Count > 0)
                        {
                            currentDirectory = directoryStack.Pop();                                                    //当前是空目录,则向上递归
                        }
                        continue;
                    }

                    //扫描目录和文件
                    string[] files = null, directories = null;
                    try
                    {
                        files       = System.IO.Directory.GetFiles(currentDirectory);
                        directories = System.IO.Directory.GetDirectories(currentDirectory);

                        item.FolderCount += directories.Length;
                        item.FileCount   += files.Length;
                    }
                    catch (Exception)
                    {
                        TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                        OnFileSystemOperationError(new FileSystemOperationErrorEventArgs(FileSystemOperationType.QueryDirectory, item.FullPath, task.RemoteHost));
                        return;
                    }

                    //优先发送文件
                    foreach (var f in files)
                    {
                        if (!PerformSendDirectory_SendFilesInDirectory(f, stream, task, item, needUpdateTotal))
                        {
                            return;
                        }
                    }

                    //扫描子目录
                    if (directories.Length > 0)
                    {
                        directoryStack.Push("");
                        Array.ForEach(directories, s => { directoryStack.Push(s); });
                        currentDirectory = directoryStack.Pop();                                //取出一个文件夹来发送
                    }
                    else
                    {
                        //如果没有子目录,则置空当前目录,以命令流程向上返回
                        currentDirectory = null;
                    }
                }
                if (item.State != FileTaskItemState.Failure)
                {
                    TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Finished);
                }
            }
        }

        //发送文件夹中的文件
        bool PerformSendDirectory_SendFilesInDirectory(string path, NetworkStream stream, FileTaskInfo task, FileTaskItem item, bool updateTotal)
        {
            System.IO.FileInfo fileinfo = new System.IO.FileInfo(path);
            if (!fileinfo.Exists)
            {
                OnFileSystemOperationError(new FileSystemOperationErrorEventArgs(FileSystemOperationType.OpenFileToSend, path, task.RemoteHost));
            }

            if (updateTotal)
            {
                item.TotalSize += (ulong)fileinfo.Length;
            }
            item.CurrentName           = fileinfo.Name;
            item.CurrentFileTransfered = 0;
            item.CurrentFileSize       = (ulong)fileinfo.Length;

            string strCMD = string.Format(":{0}:{1:x}:{2:x}:", fileinfo.Name, fileinfo.Length, (int)Consts.Cmd_FileType_Option.Regular);

            byte[] bytes = null;
            if (task.RemoteHost.IsEnhancedContractEnabled)
            {
                bytes = System.Text.Encoding.Unicode.GetBytes(strCMD);
            }
            else
            {
                bytes = System.Text.Encoding.Default.GetBytes(strCMD);
            }

            try
            {
                stream.Write(System.Text.Encoding.Default.GetBytes((bytes.Length + 4).ToString("x4")), 0, 4);
                stream.Write(bytes, 0, bytes.Length);
            }
            catch (Exception)
            {
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                return(false);
            }

            //写入文件数据
            FileStream reader = null;

            try
            {
                reader = fileinfo.OpenRead();
            }
            catch (Exception)
            {
                OnFileSystemOperationError(new FileSystemOperationErrorEventArgs(FileSystemOperationType.OpenFileToSend, path, task.RemoteHost));
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                return(false);
            }

            using (reader)
            {
                byte[] buffer = new byte[SendBuffer];
                while (item.CurrentFileTransfered < (ulong)reader.Length)
                {
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);
                    item.CurrentFileTransfered += (ulong)bytesRead;
                    item.FinishedSize          += (ulong)bytesRead;

                    try
                    {
                        stream.Write(buffer, 0, bytesRead);
                    }
                    catch (Exception)
                    {
                        TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                        return(false);
                    }
                }
                reader.Close();
            }
            item.FinishedFileCount++;

            return(true);
        }

        //发送要求创建文件命令
        bool PerformSendDirectory_SendCreateDirCommand(string path, NetworkStream stream, FileTaskInfo task, FileTaskItem item)
        {
            string strCMD = string.Format(":{0}:{1}:{2:x}:", string.IsNullOrEmpty(path) ? "." : System.IO.Path.GetFileName(path), 0, (int)(string.IsNullOrEmpty(path) ? Consts.Cmd_FileType_Option.RetParent : Consts.Cmd_FileType_Option.Dir));

            byte[] bytes = null;
            if (task.RemoteHost.IsEnhancedContractEnabled)
            {
                bytes = System.Text.Encoding.Unicode.GetBytes(strCMD);
            }
            else
            {
                bytes = System.Text.Encoding.Default.GetBytes(strCMD);
            }

            if (!string.IsNullOrEmpty(path))
            {
                item.FinishedFolderCount++;
            }

            try
            {
                stream.Write(System.Text.Encoding.Default.GetBytes((bytes.Length + 4).ToString("x4")), 0, 4);
                stream.Write(bytes, 0, bytes.Length);
                return(true);
            }
            catch (Exception)
            {
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                return(false);
            }
        }

        /// <summary>
        /// 发送单个文件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="task"></param>
        /// <param name="item"></param>
        void PerformSendFile(TcpClient client, FileTaskInfo task, FileTaskItem item)
        {
            System.IO.FileStream             fs     = null;
            System.Net.Sockets.NetworkStream writer = null;
            try
            {
                writer = client.GetStream();
            }
            catch (Exception)
            {
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                return;
            }
            try
            {
                fs = new System.IO.FileStream(item.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            }
            catch (Exception)
            {
                if (writer != null)
                {
                    writer.Close();
                }
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                OnFileSystemOperationError(new FileSystemOperationErrorEventArgs(FileSystemOperationType.OpenFileToSend, item.FullPath, task.RemoteHost));

                return;
            }
            using (fs)
            {
                //检测断点数据是否正确
                if (item.CurrentFileTransfered < 0 || item.CurrentFileTransfered > (ulong)fs.Length)
                {
                    item.CurrentFileTransfered = 0;
                }
                fs.Seek((long)item.CurrentFileTransfered, System.IO.SeekOrigin.Begin);

                //设置当前任务信息
                item.CurrentFileSize = (ulong)fs.Length;
                TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Processing);
                item.StartTime = DateTime.Now;

                using (writer)
                {
                    byte[] buffer = new byte[SendBuffer];                       //缓冲区

                    while (item.CurrentFileTransfered < item.CurrentFileSize)
                    {
                        int bytesRead = fs.Read(buffer, 0, buffer.Length);
                        try
                        {
                            writer.Write(buffer, 0, bytesRead);
                        }
                        catch (Exception)
                        {
                            TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Failure);
                            break;
                        }

                        //更新进度
                        item.CurrentFileTransfered += (ulong)bytesRead;
                        item.FinishedSize          += (ulong)bytesRead;
                    }
                    item.FinishedFileCount++;
                    writer.Close();
                }
                fs.Close();
                //标记任务完成
                if (item.State != FileTaskItemState.Failure)
                {
                    TaskManager.MarkSendTaskItemState(item, FileTaskItemState.Finished);
                }
            }
        }

        /// <summary>
        /// 解析请求的命令
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="startIndex"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        Message ParseSendCommand(byte[] buffer, int startIndex, int length)
        {
            byte[] cmdInfo = new byte[length];
            Array.Copy(buffer, 0, cmdInfo, 0, length);

            if (!MessagePacker.Test(cmdInfo))
            {
                return(null);
            }
            Message msg = MessagePacker.TryToTranslateMessage(cmdInfo, null);

            if (msg == null || (msg.Command != Consts.Commands.GetDirFiles && msg.Command != Consts.Commands.GetFileData))
            {
                return(null);
            }

            return(msg);
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="buffer">缓冲区</param>
        /// <returns></returns>
        int ReceiveByBuffer(TcpClient client, byte[] buffer)
        {
            try
            {
                return(client.Client.Receive(buffer));
            }
            catch (Exception)
            {
                //网络异常
                return(-1);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="buffer">缓冲区</param>
        /// <returns></returns>
        int ReceiveByBuffer(TcpClient client, byte[] buffer, int length)
        {
            try
            {
                return(client.Client.Receive(buffer, length, SocketFlags.None));
            }
            catch (Exception)
            {
                //网络异常
                return(-1);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="buffer">缓冲区</param>
        /// <returns></returns>
        int ReceiveByBuffer(NetworkStream stream, byte[] buffer)
        {
            try
            {
                return(stream.Read(buffer, 0, buffer.Length));
            }
            catch (Exception)
            {
                //网络异常
                return(-1);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="buffer">缓冲区</param>
        /// <returns></returns>
        int ReceiveByBuffer(NetworkStream stream, byte[] buffer, int length)
        {
            try
            {
                return(stream.Read(buffer, 0, length));
            }
            catch (Exception)
            {
                //网络异常
                return(-1);
            }
        }

        #endregion

        #region 接收文件

        /// <summary>
        /// 请求接收文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _taskManager_FileReceiveRequired(object sender, FileReceiveRequiredEventArgs e)
        {
            if (!IsInitialized)
            {
                return;
            }

            new Thread(() => { PerformFileReceive(e.Task, e.Item); })
            {
                IsBackground = true
            }.Start();
        }