Inheritance: System.IO.Stream, IDisposable
Exemple #1
0
        public WebTCPClient( MainForm UseForm, TcpClient UseClient, string UseAddress )
        {
            MForm = UseForm;
            RemoteAddress = UseAddress;

            LastTransactTime = new ECTime();
            LastTransactTime.SetToNow();
            LinesDictionary = new Dictionary<string, string>();

            if( UseClient == null )
              Client = new TcpClient();
            else
              Client = UseClient;

            try
            {
            NetStream = Client.GetStream();
            }
            catch( Exception Except )
              {
              MForm.ShowWebListenerFormStatus( "Exception in Creating the NetStream:" );
              MForm.ShowWebListenerFormStatus( Except.Message );
              NetStream = null;
              return;
              }

            Client.ReceiveTimeout = 3 * 1000;
            Client.SendTimeout = 3 * 1000;
            Client.SendBufferSize = 1024 * 32;
        }
        //Méthode statique pour l'envoi et la réception
        public void Send(Paquet paquet, NetworkStream stream)
        {
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(stream, paquet);
            stream.Flush();
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient("127.0.0.1", 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);

                String response = sr.ReadLine();

                DelegateResponse dr = writeResponse;
                dr(response);
                // rawdata = imei@lat@lng@timestamp
                string rawData = imei.ToString();
                rawData += "@" + randomCoordinates();

                rawData +="@"+ ConvertToTimestamp(DateTime.Now).ToString();
                

                 String data = stringToHexa(rawData);

                sw.WriteLine(data);
                sw.Flush();

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                //  throw;
            }
        }
 public DeveConnection(TcpClient tcpClient, DevePeer peer)
 {
     receiveBuffer = new byte[bufferSize];
     this.tcpClient = tcpClient;
     this.networkStream = tcpClient.GetStream();
     this.peer = peer;
 }
        private void btnConnect_Click(object sender, EventArgs e)
        {


            try
            {
                client = new TcpClient("127.0.0.1", 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);

                String response = sr.ReadLine();

                DelegateResponse dr = writeResponse;
                dr(response);

                randomCoordinates();

                string rawData = "Hola mundo";
                String data = stringToHexa(rawData);
                //Console.WriteLine(data);
                sw.WriteLine(data);
                sw.Flush();

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                throw;
            }
        }
        internal Connection(Socket ClientSocket, NetworkStream ClientStream)
        {
            this.ClientSocket = ClientSocket;
            this.ClientStream = ClientStream;

            this.Reader = new WebSocketFrameReader(ClientStream);
        }
        private Thread ziThread; //处理客户端请求的线程

        #endregion Fields

        #region Constructors

        public Agent(TcpClient client, NetworkStream streamToClient, string DataSourceIpOrPortA, string DataSourceIpOrPortB)
        {
            this.client = client;
            this.streamToClient = streamToClient;
            this.DataSourceIpOrPortA = DataSourceIpOrPortA;
            this.DataSourceIpOrPortB = DataSourceIpOrPortB;
        }
Exemple #8
0
        public override void Write(ref NetworkStream netstream)
        {
            using (Stream stream = new MemoryStream())
            {
                // write id
                stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2);

                // write body size
                stream.Write(BitConverter.GetBytes(0), 0, 4);

                // write isAdult
                stream.WriteByte(BitConverter.GetBytes(this.isAdult)[0]);

                // write UnderFifteen
                stream.WriteByte(BitConverter.GetBytes(this.UnderFifteen)[0]);

                // write Family
                stream.WriteByte(BitConverter.GetBytes(this.Family)[0]);

                // write Status
                stream.WriteByte(this.Status);

                // write LastDay
                stream.Write(BitConverter.GetBytes(this.LastDay), 0, 2);

                // write PayType
                stream.WriteByte(this.PayType);

                // copy stream to netstream
                stream.Position = 0;
                stream.CopyTo(netstream);
            }
        }
 public ConnectionContext(NetworkStream clientStream, string connString, TcpTestServer3 server, TaskLoggingHelper log)
 {
     this.clientStream = clientStream;
     this.connString = connString;
     this.tcpServer = server;
     this.log = log;
 }
Exemple #10
0
        internal TLSTCPClient( MainForm UseForm, TcpClient UseClient, string UseAddress )
        {
            MForm = UseForm;
            RemoteAddress = UseAddress;

            RawBuffer = new byte[RawBufferLength];
            TLSOuterRecordBuffer = new byte[MaximumTLSRecordLength + 5]; // Plus 5 for the header.

            LastTransactTime = new ECTime();
            LastTransactTime.SetToNow();

            if( UseClient == null )
              Client = new TcpClient();
            else
              Client = UseClient;

            try
            {
            NetStream = Client.GetStream();
            }
            catch( Exception Except )
              {
              MForm.ShowTLSListenerFormStatus( "Exception in Creating the NetStream:" );
              MForm.ShowTLSListenerFormStatus( Except.Message );
              NetStream = null;
              return;
              }

            Client.ReceiveTimeout = 3 * 1000;
            Client.SendTimeout = 3 * 1000;
            Client.SendBufferSize = 1024 * 32;
        }
 public AbsTcpCommunication(TcpClient sock)
 {
     _sock = sock;
     _socketStream = _sock.GetStream ();
     _in = new StreamReader (_socketStream);
     _out = new StreamWriter (_socketStream);
 }
        /// <inheritdoc />
        protected override void EstablishConnectionSpecific()
        {
            if (btClient == null) ConnectSocket();

            //We should now be able to set the connectionInfo localEndPoint
            var localEndPoint = btClient.Client.LocalEndPoint as BluetoothEndPoint;
            localEndPoint = new BluetoothEndPoint(localEndPoint.Address, ConnectionInfo.RemoteBTEndPoint.Service, localEndPoint.Port);

            NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteEndPoint, localEndPoint);
            ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint);

            btClient.Client.ReceiveBufferSize = NetworkComms.MaxReceiveBufferSizeBytes;
            btClient.Client.SendBufferSize = NetworkComms.SendBufferSizeBytes;

            //We are going to be using the networkStream quite a bit so we pull out a reference once here
            btClientNetworkStream = btClient.GetStream();
                        
            //Start listening for incoming data
            StartIncomingDataListen();

            //If the application layer protocol is enabled we handshake the connection
            if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
                ConnectionHandshake();
            else
            {
                //If there is no handshake we can now consider the connection established
                TriggerConnectionEstablishDelegates();

                //Trigger any connection setup waits
                connectionSetupWait.Set();
            }            
        }
        /// <summary>
        /// Reads a partially observable level state update from the server.
        /// </summary>
        private async Task ReadVisibleLevelState(NetworkStream stream)
        {
            Time = await _stream.ReadUInt64();
            PlayerPosition = await _stream.ReadPosition();

            // removed lock
            int roomCount = await _stream.ReadInt32();
            for (int i = 0; i < roomCount; ++i)
            {
                // Each room is identified by its rectangle.
                var rect = await _stream.ReadRectangle();

                var vis = _visibility.FirstOrDefault(x => x.Rect == rect);

                if (vis == null)
                {
                    vis = new RoomVisibility(rect);
                    _visibility.Add(vis);
                }

                int tileCount = await _stream.ReadInt32();
                for (int j = 0; j < tileCount; ++j)
                {
                    var pos = await _stream.ReadPosition();
                    vis.Reveal(pos, await TileAppearance.Read(pos, stream), Time);
                }
            }

            LoadedLevel = true;


            Program.Draw(this);

            Interface.Display.Write(0, 0, Time.ToString());
        }
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
Exemple #15
0
 public ChatClient()
 {
     this.client = new TcpClient();
     this.stream = null;
     this.listening = false;
     this.listener = new Thread(this.listen);
 }
Exemple #16
0
        /// <summary>
        /// 获取通信返回信息
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static void Work(string cmd, NetworkStream stream)
        {
            Byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(cmd);
            stream.Write(buffer, 0, buffer.Length);

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

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

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

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

            }
        }
Exemple #17
0
        public void ConnectToServer()
        {
            try
            {
                ircClient = new TcpClient(server, port);
                ns = ircClient.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);

                sw.WriteLine("NICK " + nick + "\n\r");
                sw.WriteLine("USER " + name + " " + name + " " + name + " " + server + " :" + name + " RuNnNy's Client\n\r");
                sw.WriteLine("AUTH " + auth + "\n\r");
                sw.WriteLine(sr.ReadLine());
                sw.Flush();

                Console.WriteLine("Connected to " + server + ":" + port);
                if (ircClient.Connected)
                {
                    new Thread(delegate() { while (ircClient.Connected) { IRCOut(); } }).Start();
                    new Thread(delegate() { while (ircClient.Connected) { Console.Write("{"+server+"}"+" #"+chan+": "); IRCIn(Console.ReadLine()); } }).Start();
                }
            }
            catch
            {
                Console.WriteLine("Error Connecting to Server");
            }
        }
 public override void Disconnect()
 {
     ExceptionHelper.InvalidOperationIf(!IsConnected);
     IsConnected = false;
     _stream.Dispose();
     _stream = null;
 }
Exemple #19
0
 internal override bool Auth(NetworkStream stream)
 {
     var reader = new BinaryReader(stream);
     var writer = new BinaryWriter(stream);
     try
     {
         int ver = reader.ReadByte();
         if(ver != 0x05)
         {
             throw new Exception();
         }
         string login = reader.ReadString();
         string password = reader.ReadString();
         bool result = _callback(login, password);
         if(result)
         {
             writer.Write(new byte[] { 0x05, 0x00 });
             return true;
         }
         writer.Write(new byte[] { 0x05, 0xFF });
     }
     catch(IOException)
     {}
     catch
     {
         writer.Write(new byte[] { 0x05, 0xFF });
     }
     return false;
 }
Exemple #20
0
 public SslStream(
   NetworkStream innerStream,
   bool leaveInnerStreamOpen,
   RemoteCertificateValidationCallback userCertificateValidationCallback
 ) : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback)
 {
 }
Exemple #21
0
        public bool ConnectToSphero(string spheroName)
        {
            if (_client == null)
                return false;

            if (_peers == null)
                return false;

            var device = _peers.FirstOrDefault(x => x.DeviceName == spheroName);
            if (device == null)
                return false;

            try
            {
                var serviceClass = BluetoothService.SerialPort;
                var ep = new BluetoothEndPoint(device.DeviceAddress, serviceClass);
                _client.Connect(ep);
                _stream = _client.GetStream();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemple #22
0
 public Main(string userName, string serverSocket, NetworkStream stream)
     : this()
 {
     UserName = userName;
     ServerSocket = serverSocket;
     Stream = stream;
 }
Exemple #23
0
 public bool Login(
     string username,
     string password,
     Enums.OnlineStatus onlineStatus = Enums.OnlineStatus.Online,
     Enums.DeviceType deviceType = Enums.DeviceType.Android)
 {
     try
     {
         Current = this;
         PacketManager.InitializeHandlers();
         CommandManager.InitializeCommands();
         Username = username;
         Password = password;
         OnlineStatus = onlineStatus;
         DeviceType = deviceType;
         _tcpClient = new TcpClient(_host, _port);
         Current = this;
         _networkStream = _tcpClient.GetStream();
         SendPacket(PacketTemplates.Logon(Username, DeviceType));
         _networkStream.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, null);
         Console.WriteLine(_buffer.Length);
         return true;
     }
     catch (Exception a)
     {
         return false;
     }
 }
Exemple #24
0
 public static async Task SendTransportPacket(NetworkStream sw, TransportPacketType type, byte[] Data)
 {
     TransportPacket tp = new TransportPacket(Data, type, Constants.TransportVersion);
     byte[] msg = PacketCodec.CreateTransportPacket(tp);
     sw.Write(msg, 0, msg.Length);
     await sw.FlushAsync();
 }
Exemple #25
0
        internal Response(NetworkStream stream)
        {
            string response;

            m_responses = new Queue();

            do
            {
                response = GetLine(stream);

                try
                {
                    m_code = InvalidCode;
                    m_code = int.Parse(response.Substring(0, 3));
                }
                catch
                {
                    throw new InvalidResponseException("Invalid response", this);
                }

                m_responses.Enqueue(response);
            }
            while (response.Length >= 4 && response[3] == '-');

            if (m_code == ServiceUnavailable)
                throw new ServerDownException(this);
        }
        public OutboundPacket(NetworkStream stream, String command)
        {
            command = "!1" + command;
            int dataSize = command.Length + _packetFooter.Length;
            int packetSize = _packetHeaderTotalSize + dataSize;

            byte[] message = new byte[packetSize];
            int pos = 0;

            foreach (byte b in _packetHeader)
                message[pos++] = b;

            foreach (byte b in BitConverter.GetBytes(dataSize).Reverse())
                message[pos++] = b;

            message[pos++] = _protocolVersion;
            pos += 3;

            foreach (byte b in System.Text.Encoding.ASCII.GetBytes(command))
                message[pos++] = b;

            foreach (byte b in _packetFooter)
                message[pos++] = b;
            stream.Write(message, 0, message.Length);
            try { System.Threading.Thread.Sleep(100); } catch (Exception) { }
        }
Exemple #27
0
 private async void ReadAsync(NetworkStream stream)
 {
     byte[] buffer = new byte[100];
     while (true)
     {
         try
         {
             int length = await stream.ReadAsync(buffer, 0, buffer.Length);
             Invoke(new MethodInvoker(delegate
             {
                 outputText.Append(buffer, length);
             }));
         }
         catch
         {
             if (this.Visible)
             { // we're not being closed
                 Invoke(new MethodInvoker(delegate
                 {
                     Stop();
                 }));
             }
             break;
         }
     }
 }
Exemple #28
0
        public void Write(NetworkStream stream)
        {
            stream.WriteByte((byte)this.Type);
            StreamHelper.WriteString(stream, this.Username);

            stream.Flush();
        }
 public NetworkClient(System.Net.IPAddress serverAddress, int port)
 {
     TcpClient client = new TcpClient();
     client.Connect(serverAddress, port);
     _stream = client.GetStream();
     _connected = true;
     BackgroundWorker streamWorker = new BackgroundWorker();
     streamWorker.WorkerSupportsCancellation = true;
     streamWorker.DoWork += ReadFromStream;
     streamWorker.RunWorkerCompleted += (s, a) =>
                                     {
                                         if (_connected)
                                         {
                                             streamWorker.RunWorkerAsync(_stream);
                                         }
                                     };
     streamWorker.RunWorkerAsync(_stream);
     StreamError += (ex, stream) =>
                     {
                         if (ex is IOException || ex is InvalidOperationException || ex is ObjectDisposedException)
                         {
                             _connected = false;
                             Console.WriteLine("Lost connection: {0}", ex.Message);
                             Console.Write("> ");
                         }
                         else
                         {
                             throw ex;
                         }
                     };
 }
Exemple #30
0
        /// <summary>
        /// Blocking call to read a full Message object from a given stream
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static Message ReadMessage(NetworkStream stream)
        {
            Debug.Assert(stream.CanRead);

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

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

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

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

            // Deserialize the message
            return Message.Deserialize(messageBytes);
        }
Exemple #31
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>    
 /// 初始化一个网路访问数据流    
 /// </summary>   
 /// <returns></returns>     
 public NetworkStream BuildStream()
 {
     System.Net.Sockets.NetworkStream stream = null;
     return stream;
 }
Exemple #33
0
 internal static void Send(System.Net.Sockets.NetworkStream ns, NewPayLoad pl)
 {
     byte[] b = pl.GetPackage();
     ns.Write(b, 0, b.Length);
     ns.Flush();
 }
Exemple #34
0
        public void receiveFromRobotController()
        {
            String incomingMessage     = "";
            String incomingMessageTemp = "";

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

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


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

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

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

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

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

                            // Fire the receive event and save sensor values to database
                            if (this.messageReceivedEvent != null)
                            {
                                this.messageReceivedEvent(msgArray);
                            }
                            //if (this.tunnelingMessage != null) this.tunnelingMessage(incomingMessageTemp);
                            // Test to use one thread for tunneling to client and to filtering...
                            //sendToPhone(incomingMessageTemp);
                            //if(globalDataSet.DebugMode) Debug.Write("Message received: " + incomingMessageTemp + "\n");
                            msgArray            = new String[] { "", "" };
                            incomingMessageTemp = "";
                        }
                    }
                }
                catch (System.IO.IOException ex)
                {
                    // TODO Validate shutdown implementation
                    this.shutDown = true;
                }
            }
        }
Exemple #35
0
        private async Task ProcessRequest(TcpListener listener, CancellationToken token)
        {
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                //System.Threading.Thread.Sleep(100);
                TcpClient client = await listener.AcceptTcpClientAsync();

                if (token.IsCancellationRequested)
                {
                    try
                    {
                        client.Close();
                    }
                    finally
                    {
                    }
                    return;
                }

                using (System.Net.Sockets.NetworkStream netStream = client.GetStream())
                {
                    using (StreamReader reader = new StreamReader(netStream))
                    {
                        using (StreamWriter writer = new StreamWriter(netStream))
                        {
                            writer.AutoFlush = true;

                            // Show application
                            string input = string.Empty;
                            while (!input.Equals("9"))
                            {
                                // Show menu
                                writer.WriteLine("Menu:");
                                writer.WriteLine("-----");
                                writer.WriteLine("  1) Display date");
                                writer.WriteLine("  2) Display time");
                                writer.WriteLine("  9) Quit");
                                writer.WriteLine();
                                writer.Write("Your choice: ");

                                input = reader.ReadLine();
                                writer.WriteLine();

                                switch (input)
                                {
                                case "1":
                                {
                                    writer.WriteLine(String.Format("Current date: {0}", DateTime.Now.ToShortDateString()));
                                }
                                break;

                                case "2":
                                {
                                    writer.WriteLine(String.Format("Current time: {0}", DateTime.Now.ToShortTimeString()));
                                }
                                break;

                                case "9":
                                {
                                    writer.WriteLine("Thank you! ");
                                }
                                    continue;
                                }
                                writer.WriteLine();
                            }

                            // Done!
                            client.Close();
                        }
                    }
                }
            }
        }
Exemple #36
0
 public NetworkStreamTextReader(System.Net.Sockets.NetworkStream stream)
 {
     this.stream = stream;
     stream.BeginRead(readBuffer, 0, readBuffer.Length, new System.AsyncCallback(CB), null);
 }
    public static void Main()
    {
        IPAddress  myIP         = IPAddress.Parse("127.0.0.1");
        IPEndPoint myIpEndPoint = new IPEndPoint(myIP, 8888);

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

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

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

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

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

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

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

            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            resMsg = resMsg.TrimEnd('\n');
            Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(resMsg);
            bool isContainTip = dic.ContainsKey("tip_username");
            commentNo++;
            if (isContainTip)
            {
                resMsg = commentNo.ToString() + "\t" + dic["time"].Replace("\t", " ") + "\t" + dic["username"].Replace("\t", " ") + "\t" + dic["comment"].Replace("\t", " ") + "\t" + "1";
            }
            else
            {
                resMsg = commentNo.ToString() + "\t" + dic["time"].Replace("\t", " ") + "\t" + dic["username"].Replace("\t", " ") + "\t" + dic["comment"].Replace("\t", " ") + "\t" + "0";
            }
            ms.Close();
            messages.Enqueue(resMsg);
            if (messages.Count > 500)
            {
                messages.Dequeue();
            }
            try {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(@"FC2.log", false, System.Text.Encoding.GetEncoding("utf-8"));
                sw.Write(string.Join("\n", messages.ToArray()));
                sw.Close();
            } catch (Exception e) {
                Console.WriteLine("System.IO.StreamWriter: " + e.ToString());
            }
            Console.WriteLine("{0}", resMsg);
        }
    }
Exemple #38
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
            {
            }
        }
Exemple #39
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();
        }
Exemple #40
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";
        // 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);

        // サーバから送られたデータを受信する
        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("切断しました.");

        Console.ReadLine();
    }
Exemple #41
0
        private static CS422.WebRequest BuildRequest(TcpClient client)
        {
            MemoryStream data     = new MemoryStream();
            StreamReader sr       = new StreamReader(data);
            DateTime     start    = DateTime.Now;
            TimeSpan     duration = TimeSpan.FromSeconds(10);

            int  currentRead = -1;
            long totalRead   = 0;

            byte[] buffer = new byte[1024];

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

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

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

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

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

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

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

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

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

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

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

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

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

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


                            return(null);
                        }
                    }
                }
            }

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

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

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

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

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

                return(null);
            }
        }
Exemple #42
0
 public void Serialize(System.Net.Sockets.NetworkStream stream, Packet obj)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     bf.Serialize(stream, obj);
 }
        /// <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());
        }
Exemple #44
0
        private void dostuff()
        {
            aaLogReader.aaLogReader logReader = new aaLogReader.aaLogReader();
            //txtLog.Text = "";
            try
            {
                ++totalCount;

                //aaLogReader.LogRecord lastRecordRead = new LogRecord();

                Stopwatch sw = Stopwatch.StartNew();

                //int RecordsToRead = 100000;

                //addlog("Timer(ms) " + sw.ElapsedMilliseconds.ToString());
                //addlog("Actual Records " + records.Count.ToString());
                //addlog("Rate (records/s): " + ((int)(1000.0 * (float)records.Count / (float)sw.ElapsedMilliseconds)).ToString());
                //addlog("");
                //addlog(JsonConvert.SerializeObject(records, Formatting.Indented));
                ////lastRecordRead = logReader.ReadStatusCacheFile();
                //addlog(JsonConvert.SerializeObject(lastRecordRead, Formatting.Indented));
                //addlog("");
                //addlog(JsonConvert.SerializeObject(logReader.ReadLogHeader(), Formatting.Indented));
                ////Debug.Print(JsonConvert.SerializeObject(record,Formatting.Indented));

                List <LogRecord> records = logReader.GetUnreadRecords();

                addlog(System.DateTime.Now.ToString() + " " + records.Count.ToString());

                if (ForwardLogsCheckBox.Checked)
                {
                    // Open socket to send logs to remote host
                    TcpClient vSocket = new System.Net.Sockets.TcpClient(RemoteHost, RemotePort);
                    System.Net.Sockets.NetworkStream ServerStream = vSocket.GetStream();
                    System.IO.StreamWriter           swriter      = new StreamWriter(ServerStream);

                    foreach (LogRecord lr in records)
                    {
                        swriter.WriteLine(lr.ToKVP());
                    }

                    //swriter.Close();
                    //ServerStream.Close();
                    vSocket.Close();
                }

                ++successCount;
                failureLastTime = false;
            }
            catch (Exception ex)
            {
                ++failureCount;
                if (failureLastTime)
                {
                    ++failureConsecCount;
                }
                else
                {
                    failureConsecCount = 1;
                }
                failureLastTime = true;

                addlog("***********");
                addlog(ex.ToString());
                addlog("***********");
                log.Error(ex);
            }
            finally
            {
                if (logReader != null)
                {
                    logReader.CloseCurrentLogFile();
                }
            }
        }
Exemple #45
0
 public Packet Deserialize(System.Net.Sockets.NetworkStream stream)
 {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
     return((Packet)(bf.Deserialize(stream)));
 }
Exemple #46
0
 internal TcpClient(Socket client)
 {
     this.client = client;
     this.stream = null;
     this.active = true;
 }
Exemple #47
0
        public static DateTime GetBeijingTime(ref bool result)
        {
            DateTime dt;

            // 返回国际标准时间
            // 只使用 timeServers 的 IP 地址,未使用域名
            try
            {
                string[,] timeServers = new string[14, 2];
                int[] searchOrder = { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 };
                timeServers[0, 0]  = "time-a.nist.gov";
                timeServers[0, 1]  = "129.6.15.28";
                timeServers[1, 0]  = "time-b.nist.gov";
                timeServers[1, 1]  = "129.6.15.29";
                timeServers[2, 0]  = "time-a.timefreq.bldrdoc.gov";
                timeServers[2, 1]  = "132.163.4.101";
                timeServers[3, 0]  = "time-b.timefreq.bldrdoc.gov";
                timeServers[3, 1]  = "132.163.4.102";
                timeServers[4, 0]  = "time-c.timefreq.bldrdoc.gov";
                timeServers[4, 1]  = "132.163.4.103";
                timeServers[5, 0]  = "utcnist.colorado.edu";
                timeServers[5, 1]  = "128.138.140.44";
                timeServers[6, 0]  = "time.nist.gov";
                timeServers[6, 1]  = "192.43.244.18";
                timeServers[7, 0]  = "time-nw.nist.gov";
                timeServers[7, 1]  = "131.107.1.10";
                timeServers[8, 0]  = "nist1.symmetricom.com";
                timeServers[8, 1]  = "69.25.96.13";
                timeServers[9, 0]  = "nist1-dc.glassey.com";
                timeServers[9, 1]  = "216.200.93.8";
                timeServers[10, 0] = "nist1-ny.glassey.com";
                timeServers[10, 1] = "208.184.49.9";
                timeServers[11, 0] = "nist1-sj.glassey.com";
                timeServers[11, 1] = "207.126.98.204";
                timeServers[12, 0] = "nist1.aol-ca.truetime.com";
                timeServers[12, 1] = "207.200.81.113";
                timeServers[13, 0] = "nist1.aol-va.truetime.com";
                timeServers[13, 1] = "64.236.96.53";
                int    portNum   = 13;
                byte[] bytes     = new byte[1024];
                int    bytesRead = 0;
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                for (int i = 0; i < 13; i++)
                {
                    string hostName = timeServers[searchOrder[i], 1];
                    try
                    {
                        client.Connect(hostName, portNum);

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

                        bytesRead = ns.Read(bytes, 0, bytes.Length);
                        client.Close();

                        break;
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }


                char[] sp = new char[1];
                sp[0] = ' ';
                dt    = new DateTime();
                string str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead);

                string[] s = str1.Split(sp);
                if (s.Length >= 2)
                {
                    dt     = DateTime.Parse(s[1] + " " + s[2]); // 得到标准时间
                    dt     = dt.AddHours(8);                    // 得到北京时间
                    result = true;
                }
                else
                {
                    result = false;
                    dt     = DateTime.Parse("2016-1-1");
                }
            }
            catch (Exception)
            {
                result = false;
                dt     = DateTime.Parse("2016-1-1");
            }
            return(dt);
        }
Exemple #48
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";
        }
        public void receiveFromRobotController()
        {
            String incomingMessage     = "";
            String incomingMessageTemp = "";

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

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


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

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

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

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

                            //fire the receiveevent
                            if (this.messageReceivedEvent != null)
                            {
                                this.messageReceivedEvent(msgArray);
                            }
                            //if (this.tunnelingMessage != null) this.tunnelingMessage(incomingMessageTemp);
                            // Test to use one thread for tunneling to client and to filtering...
                            sendToPhone(incomingMessageTemp);
                            msgArray            = new String[] { "", "" };
                            incomingMessageTemp = "";
                        }
                    }
                }
                catch (System.IO.IOException ex)
                {
                    this.shutDown = true;
                    Diagnose form1 = new Diagnose();
                    form1.setButtonText("Start");
                }
            }
        }
Exemple #50
0
        public static DateTime DataStandardTime()
        {//返回国际标准时间
            //只使用的时间服务器的IP地址,未使用域名
            int serverNum = 14;

            string[,] 时间服务器 = new string[serverNum, 2];
            int[] 搜索顺序 = new int[] { /*14, 13 ,*/ 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 };
            时间服务器[0, 0]  = "time-a.nist.gov";
            时间服务器[0, 1]  = "129.6.15.28";
            时间服务器[1, 0]  = "time-b.nist.gov";
            时间服务器[1, 1]  = "129.6.15.29";
            时间服务器[2, 0]  = "time-a.timefreq.bldrdoc.gov";
            时间服务器[2, 1]  = "132.163.4.101";
            时间服务器[3, 0]  = "time-b.timefreq.bldrdoc.gov";
            时间服务器[3, 1]  = "132.163.4.102";
            时间服务器[4, 0]  = "time-c.timefreq.bldrdoc.gov";
            时间服务器[4, 1]  = "132.163.4.103";
            时间服务器[5, 0]  = "utcnist.colorado.edu";
            时间服务器[5, 1]  = "128.138.140.44";
            时间服务器[6, 0]  = "time.nist.gov";
            时间服务器[6, 1]  = "192.43.244.18";
            时间服务器[7, 0]  = "time-nw.nist.gov";
            时间服务器[7, 1]  = "131.107.1.10";
            时间服务器[8, 0]  = "nist1.symmetricom.com";
            时间服务器[8, 1]  = "69.25.96.13";
            时间服务器[9, 0]  = "nist1-dc.glassey.com";
            时间服务器[9, 1]  = "216.200.93.8";
            时间服务器[10, 0] = "nist1-ny.glassey.com";
            时间服务器[10, 1] = "208.184.49.9";
            时间服务器[11, 0] = "nist1-sj.glassey.com";
            时间服务器[11, 1] = "207.126.98.204";
            时间服务器[12, 0] = "nist1.aol-ca.truetime.com";
            时间服务器[12, 1] = "207.200.81.113";
            时间服务器[13, 0] = "nist1.aol-va.truetime.com";
            时间服务器[13, 1] = "64.236.96.53";

            /*时间服务器[14, 0] = "ntp.sjtu.edu.cn";
             * 时间服务器[14, 1] = "202.120.2.101";
             * 时间服务器[15, 0] = "s2m.time.edu.cn";
             * 时间服务器[15, 1] = "202.112.7.13";
             * */
            int    portNum = 13;
            string hostName;

            byte[] bytes     = new byte[1024];
            int    bytesRead = 0;

            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            for (int i = 0; i < serverNum; i++)
            {
                hostName = 时间服务器[搜索顺序[i], 1];
                try
                {
                    client.Connect(hostName, portNum);
                    System.Net.Sockets.NetworkStream ns = client.GetStream();
                    bytesRead = ns.Read(bytes, 0, bytes.Length);
                    client.Close();
                    break;
                }
                catch (System.Exception)
                {
                }
            }

            try
            {
                char[] sp = new char[1];
                sp[0] = ' ';
                System.DateTime dt = new DateTime();
                string          str1;
                str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead);

                string[] s;
                s  = str1.Split(sp);
                dt = System.DateTime.Parse(s[1] + " " + s[2]); //得到标准时间
                dt = dt.AddHours(8);                           //得到北京时间*/
                return(dt);
            }
            catch (System.Exception)
            {
                return(System.DateTime.Now);
            }
        }
Exemple #51
0
        public static void ClientMain()
        {
            //サーバーのIPアドレス(または、ホスト名)とポート番号
            //string ipOrHost = "192.168.43.151";
            string ipOrHost = "localhost";
            int    port     = 34481;

            bool exit = false;

            //var ipGlobalProp = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            //var usedPorts = ipGlobalProp.GetActiveTcpConnections();
            //while (usedPorts.Select(s => s.LocalEndPoint.Port).Contains(port)) {
            //    port += 1;
            //}


            ////サーバーに送信するデータを入力してもらう
            //Console.Write(" >> ");
            //string sendMsg = Console.ReadLine();
            ////何も入力されなかった時は終了
            //if (sendMsg == null || sendMsg.Length == 0) {
            //    return;
            //}


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


            System.Net.Sockets.NetworkStream ns  = tcp.GetStream();
            System.Text.Encoding             enc = System.Text.Encoding.UTF8;

            while (!exit)
            {
                //サーバーに送信するデータを入力してもらう
                Console.Write(" >> ");
                string sendMsg = Console.ReadLine();
                //何も入力されなかった時は終了
                if (sendMsg == null || sendMsg.Length == 0 || DisconnectKeyWord.Contains(sendMsg))
                {
                    exit = true;
                    //break;
                }

                //NetworkStreamを取得する

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

                //Console.ReadKey(true);

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



                    //サーバーから送られたデータを受信する
                    //bool disconnected = false;
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    byte[] resBytes           = new byte[255];

                    int resSize;
                    do
                    {
                        //データの一部を受信する
                        resSize = tcp.Client.Receive(resBytes);
                        //Readが0を返した時はサーバーが切断したと判断
                        if (resSize == 0)
                        {
                            //disconnected = true;
                            Console.WriteLine("クライアントが切断しました。");
                            break;
                        }
                        //受信したデータを蓄積する
                        ms.Write(resBytes, 0, resSize);

                        //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                        // 受信を続ける
                    } while (resBytes[resSize - 1] != '\n');
                    //受信したデータを文字列に変換
                    string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                    ms.Close();
                    //末尾の\nを削除
                    resMsg = resMsg.TrimEnd('\n');

                    Console.CursorLeft = 0;
                    Console.WriteLine(resMsg);
                    Console.WriteLine(">>");
                } catch (Exception e) {
                    Console.WriteLine(e);
                    exit = true;
                }
            }


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

            //Console.ReadLine();
        }
Exemple #52
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);
        }
Exemple #53
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();
        }
Exemple #54
0
    private void IRCInputProcedure(System.IO.TextReader input, System.Net.Sockets.NetworkStream networkStream)
    {
        while (!_stopThreads)
        {
            try
            {
                if (!networkStream.DataAvailable)
                {
                    Thread.Sleep(20);
                    continue;
                }

                _buffer = input.ReadLine();
                if (_buffer == null)
                {
                    continue;
                }
                //Debug.Log(_buffer);

                string[] tokens;
                string   message;
                if (_buffer.StartsWith("@"))
                {
                    var split     = _buffer.IndexOf(' ');
                    var userstate = _buffer.Substring(0, split);
                    message = _buffer.Substring(split + 1);
                    tokens  = message.Split(' ');

                    var username = tokens[0].Split('!')[0].Substring(1);
                    var keys     = userstate.Split(';');

                    foreach (var k in keys)
                    {
                        if (k.StartsWith("color="))
                        {
                            if (GetUserColor(username) != DefaultChatNameColor)
                            {
                                continue;
                            }
                            var color = (k != "color=") ? k.Substring(7) : null;
                            if (string.IsNullOrEmpty(color))
                            {
                                var r = Mathf.Max(0.25f, Random.Next(0, 100) / 100f);
                                var g = Mathf.Max(0.25f, Random.Next(0, 100) / 100f);
                                var b = Mathf.Max(0.25f, Random.Next(0, 100) / 100f);
                                color = ColorToHex(new Color(r, g, b));
                            }
                            lock (UserColors)
                            {
                                UserColors.Add(username, color);
                            }
                        }
                    }
                }
                else
                {
                    message = _buffer;
                    tokens  = _buffer.Split(' ');
                }

                switch (tokens[1])
                {
                case "PRIVMSG":
                case "NOTICE":
                    lock (_recievedMsgs)
                    {
                        _recievedMsgs.Add(message);
                    }
                    break;

                case "JOIN":
                    lock (_recievedMsgs)
                    {
                        _recievedMsgs.Add(ToTwitchNotice(string.Format("Connected to {0}!", tokens[2])));
                        _connected = true;
                    }
                    break;

                case "001":
                    lock (_recievedMsgs)
                    {
                        _recievedMsgs.Add(ToTwitchNotice("Logged in! Connecting to chat.."));
                        _loggedin = true;
                    }
                    SendCommand("CAP REQ :twitch.tv/tags");
                    SendCommand("CAP REQ :twitch.tv/commands");
                    SendCommand("JOIN #" + ChannelName);
                    break;

                case "CAP":
                    lock (_recievedMsgs)
                    {
                        _recievedMsgs.Add(ToTwitchNotice("Acknowledging Client Capabilities!"));
                    }
                    break;

                case "USERSTATE":
                    break;

                default:
                    if (_buffer.StartsWith("PING "))
                    {
                        SendCommand(_buffer.Replace("PING", "PONG"));
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                lock (_recievedMsgs)
                {
                    _recievedMsgs.Add(ToNotice("EXCEPTION", e.ToString(), NoticeColor.Red));
                }
            }
        }
    }
Exemple #55
0
 /// <summary>
 /// Initializes a new instance of the NetworkStream class
 /// </summary>
 /// <param name="stream">Implementação de network stream do .NET Framework</param>
 public NetworkStream(Sockets.NetworkStream stream)
 {
     this.stream = stream;
 }