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

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

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                this.m_ErrorCount += 1;
                if(this.m_ErrorCount < 10)
                {
                    System.Threading.Thread.Sleep(5000);
                    this.TryPrint(zplCommands);
                }
                else
                {
                    throw ex;
                }
            }
        }
Beispiel #2
1
        void ConnectionTask()
        {
            try
               {
               IsInConnectionTask=true;
               while (true)
               {
                   client = new System.Net.Sockets.TcpClient();
                   try
                   {
                       Console.WriteLine("try to  connect " + ip + ":" + port + " !");
                       client.Connect(ip, port);
                       Console.WriteLine(ip + ":" + port + "connected! ");
                   }
                   catch (Exception ex)
                   {
                       Console.WriteLine(ip + ":" + port + " " + ex.Message);
                   }

                   if (client.Connected)
                   {
                       new System.Threading.Thread(ReceiveTask).Start();
                       return;
                   }

               }
               }
               catch { ;}
               finally
               {
               IsInConnectionTask = false;
               }
        }
Beispiel #3
0
 public static async Task<OpcWriter> CreateAsync(string host, int port = DefaultPort)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(host, port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
Beispiel #4
0
 public static OpcWriter Create(IPEndPoint target)
 {
     var client = new System.Net.Sockets.TcpClient();
     client.Connect(target.Address, target.Port);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
Beispiel #5
0
 public static OpcWriter Create(string host, int port = DefaultPort)
 {
     var client = new System.Net.Sockets.TcpClient();
     client.Connect(host, port);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
Beispiel #6
0
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>
        /// SocketException is resolved at higher level in the
        /// RemoteObjectProxyProvider.ProxyInterceptor.Intercept() method.
        /// </remarks>
        /// <param name="command"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <exception cref="System.Net.Sockets.SocketException">
        /// When it is not possible to connect to the server.
        /// </exception>
        public string Request(string command, string[] data)
        {
            var client = new System.Net.Sockets.TcpClient(ServerAddress.IPAddress.ToString(), ServerAddress.Port);
            using (var clientStream = client.GetStream())
            {
                var sw = new StreamWriter(clientStream);

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

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

                sw.Flush();

                var sr = new StreamReader(clientStream);
                string result = sr.ReadLine();
                if (result != null)
                {
                    result = result
                        .Replace(TcpServer.CarriageReturnReplacement, "\r")
                        .Replace(TcpServer.LineFeedReplacement, "\n");
                }
                return result;
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            Protocol protocol;
             string ip;
             int port;
             V2DLE dle;
             System.Net.Sockets.TcpClient tcp;
            protocol = new Protocol();
            protocol.Parse(System.IO.File.ReadAllText(Protocol.CPath(AppDomain.CurrentDomain.BaseDirectory+"TIME.txt")),false);
            ip = protocol.ip;
            port = protocol.port;

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

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

                        System.Threading.Thread.Sleep(1000 * 60 );
                    }
                }
                catch (Exception ex)
                {
                    ;
                }
            }
        }
        public static string connect(String server,int port,String ouath)
        {
            System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient ();
            sock.Connect (server, port);
            if (!sock.Connected) {
                Console.Write ("not working hoe");

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

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

            );
            output.Flush ();

            for (String rep = input.ReadLine ();; rep = input.ReadLine ()) {
                string[] splitted = rep.Split (':');
                if (splitted.Length > 2) {
                    string potentialVote = splitted [2];
                    if (Array.Exists (validVotes, vote => vote.Equals(potentialVote)))
                        return potentialVote;
                }
            }
        }
Beispiel #9
0
 public static async Task<OpcWriter> CreateAsync(IPEndPoint target)
 {
     var client = new System.Net.Sockets.TcpClient();
     await client.ConnectAsync(target.Address, target.Port).ConfigureAwait(false);
     var stream = client.GetStream();
     return new OpcWriter(stream, true);
 }
 public TcpClient(string hostName, int port)
 {
     _buffer = new byte[ReadSize];
     _tcpClient = new System.Net.Sockets.TcpClient(hostName, port);
     if (_tcpClient.Connected)
         _stream = _tcpClient.GetStream();
 }
Beispiel #11
0
        public chatHelper(Chat.Sockets.TcpClient tcpClient)
        {
            client = tcpClient;

            Thread chatThread = new Thread(new ThreadStart(startChat));
            chatThread.Start();
        }
Beispiel #12
0
        public static bool CheckPort(string ip, int port, int timeout)
        {
            using (System.Net.Sockets.TcpClient tcp = new System.Net.Sockets.TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(ip, port, null, null);
                System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
                    {
                        tcp.Close();
                        throw new TimeoutException();
                    }

                    tcp.EndConnect(ar);

                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
                finally
                {
                    wh.Close();
                }
            }
        }
        private static bool Connect(string friendly)
        {
            try
            {
                client = new System.Net.Sockets.TcpClient();
                TVServer.MPClient.Client mpclient = uWiMP.TVServer.MPClientDatabase.GetClient(friendly);

                if (mpclient.Hostname == string.Empty)
                {
                    host = friendly;
                }
                else
                {
                    host = mpclient.Hostname;
                }

                if (mpclient.Port == string.Empty)
                {
                    port = DEFAULT_PORT;
                }
                else
                {
                    port = Convert.ToInt32(mpclient.Port);
                }

                client.Connect(host, port);
            }
            catch (Exception ex)
            {
                return false;
            }

            return true;
        }
Beispiel #14
0
        public bool Start()
        {
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);

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

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

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

            //    throw;
            //}

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

            return true;
        }
Beispiel #15
0
        /// <summary>
        /// Open 通信要求受付(非同期)
        /// </summary>
        /// <param name="ipAddr">IPアドレス</param>
        /// <param name="ipPort">ポート</param>
        /// <returns></returns>
        public async void OpenAsync()
        {
            sw.Start();

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

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

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

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

                //NetworkStreamを取得
                ns = client.GetStream();
            }
            catch (Exception)
            {
            }
        }
        private void printButton_Click(object sender, EventArgs e)
        {
            // Printer IP Address and communication port
            string ipAddress = printerIpText.Text;
            int port = 9100;

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

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

                // Close Connection
                writer.Close();
                client.Close();
                MessageBox.Show("Print Successful!", "Success");
                this.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex);
                MessageBox.Show("No printer installed corresponds to the IP address given", "No response");
            }
        }
Beispiel #17
0
        public void Start(System.Net.Sockets.TcpClient socket)
        {
            m_theSocket = socket;

            m_theCommands = new Assemblies.Ftp.FtpConnectionObject(m_fileSystemClassFactory, m_nId, socket);
            m_theThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadRun));
            m_theThread.Start();
        }
Beispiel #18
0
 public GNIClientInformation(uint clientID, System.Net.Sockets.TcpClient tcpClient)
 {
     this.clientID = clientID;
     this.tcpClient = tcpClient;
     this.name = "Anonymous";
     this.data = new GNIDataSet(true);
     this.dataBeingTransferred = new GNIPendingData(false);
 }
Beispiel #19
0
 public Conexao(System.Net.Sockets.TcpClient client, Server server)
 {
     this.client = client;
     this.server = server;
     Stream s = client.GetStream();
     writer = new StreamWriter(s);
     reader = new StreamReader(s);
 }
Beispiel #20
0
 public Player(System.Net.Sockets.TcpClient TcpClient)
 {
     client = TcpClient;
     Thread chatTread = new Thread(new ThreadStart(login));
     Thread movement = new Thread(new ThreadStart(UserPos));
     chatTread.Start();
     movement.Start();
 }
 public TcpConnection(System.Net.Sockets.TcpClient socket)
 {
     if (socket == null)
         throw new System.NullReferenceException();
     this.socket = socket;
     in_stream = new System.IO.StreamReader(socket.GetStream());
     out_stream = new System.IO.StreamWriter(socket.GetStream());
 }
		/*
		* 
		*/
		public virtual void  openSocket()
		{
			socket = new System.Net.Sockets.TcpClient(host, port);
			socket.LingerState = new System.Net.Sockets.LingerOption(true, 1000);
			
			os = socket.GetStream();
			is_Renamed = socket.GetStream();
		}
Beispiel #23
0
 /// <summary>
 /// Start the system. This method must be called.
 /// </summary>
 /// <param name="Loop">The game loop called for each game.</param>
 public void Run(GameLoop Loop)
 {
     try
     {
         _Client = new System.Net.Sockets.TcpClient(_Server, _Port);
     }
     catch
     {
         System.Console.WriteLine("[ERROR] Impossible to join the server (FATAL)");
         System.Environment.Exit(1);
     }
     JSON.Object connect = new JSON.Object();
     connect["login"] = _Username;
     connect["password"] = _Password;
     _Write(connect);
     try
     {
         while (true)
         {
             JSON.Object newgame = _ReadObject();
             Game game = new Game();
             game._Parent = this;
             try
             {
                 if ((newgame["error"] as JSON.String).Value != "")
                 {
                     Console.WriteLine("[ERROR] Invalid connection check your login and your password");
                     System.Environment.Exit(1);
                 }
             }
             catch { }
             try { game.You._Name = (newgame["you"] as JSON.String).Value; }
             catch { game.You._Name = "noname"; }
             try { game.Challenger._Name = (newgame["challenger"] as JSON.String).Value; }
             catch { game.Challenger._Name = "noname"; }
             Loop(game);
             if (!game._Ended)
             {
                 System.Console.WriteLine("[ERROR] Game loop has ended before the end of the game (FATAL)");
                 System.Environment.Exit(1);
             }
             JSON.Object ready = new JSON.Object();
             ready["type"] = "ready";
             _Write(ready);
             System.Threading.Thread.Sleep(10);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("[INFO]  An exception occurs inside the game loop:\n" + e.ToString());
     }
     try
     {
         _Client.Close();
     }
     catch { }
 }
        public bool client_coneciton()
        {
            client = new System.Net.Sockets.TcpClient(IP_add, port);
            ns = client.GetStream();
            ns.ReadTimeout = 10000;
            ns.WriteTimeout = 10000;

            return true;
        }
 public DoCommunicate(System.Net.Sockets.TcpClient tcpClient)
 {
     //create our TcpClient
     client = tcpClient;
     //create a new thread
     Thread chatThread = new Thread(new ThreadStart(startChat));
     //start the new thread
     chatThread.Start();
 }
        public void connectClient(string ip, int port)
        {
            myip = ip;
            myport = port;
            xclient = new System.Net.Sockets.TcpClient();

            System.Net.IPAddress addr = System.Net.IPAddress.Parse(ip);
            xclient.Connect(new System.Net.IPEndPoint(addr, port));
        }
Beispiel #27
0
        static void Main(string[] args)
        {
            CreateServerCode();
            return;

            System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
            client.Connect("210.245.121.245", 4530);
            Console.WriteLine("Ok");
        }
Beispiel #28
0
 public void checkAvailability(object sender, System.ComponentModel.DoWorkEventArgs e) {
     try {
         System.Net.Sockets.TcpClient clnt = new System.Net.Sockets.TcpClient("smtp.gmail.com", 587);
         clnt.Close();
         e.Result = EmailResponse.ServerReachable;
     } catch {
         e.Result = EmailResponse.ServerUnreachable;
     }
 }
Beispiel #29
0
 private void checkAvailability(object sender, System.ComponentModel.DoWorkEventArgs e)
 {
     try {
         System.Net.Sockets.TcpClient clnt=new System.Net.Sockets.TcpClient("smtp.gmail.com",587);
         clnt.Close();
         email_available = true;
     } catch {
         email_available = false;
     }
 }
 static string WritePJL(string Type, string Address, string Command)
 {
     System.IO.Stream T = null;
     try {
         System.Net.Sockets.TcpClient TC;
         if (Type == "usb")
         {
             T = System.IO.File.Open(Address, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
         }
         else if (Type == "serial")
         {
             T = System.IO.File.Open(Address, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
         }
         else if (Type == "parallel")
         {
             T = System.IO.File.Open(Address, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite);
         }
         else if (Type == "ethernet")
         {
             TC = new System.Net.Sockets.TcpClient();
             TC.Connect(Address, 9100);
             T = TC.GetStream();
         }
         byte[] b = System.Text.Encoding.Default.GetBytes(Command);
         T.Write(b, 0, b.Length);
         byte[] b2 = new byte[1024]; int xLen = T.Read(b2, 0, 1024);
         T.Close();
         return(System.Text.Encoding.Default.GetString(b2).Substring(0, xLen));
     } catch (Exception ex) {
         if (T != null)
         {
             T.Close();
         }
         return("");
     }
 }
Beispiel #31
0
        public void Connect(int fisPort)
        {
            if (_tcpClient != null)
            {
                return;
            }

            _fisHostName = "live.fisski.com";
            _fisPort     = fisPort;

            _sequence = 0;
            try
            {
                clearScheduledTransfers();
                _tcpClient = new System.Net.Sockets.TcpClient();
                _tcpClient.Connect(_fisHostName, _fisPort);

                // Spawn receive thread
                _receiveThread = new System.Threading.Thread(receiveMethod);
                _receiveThread.Start();

                _keepAliveTimer          = new System.Timers.Timer();
                _keepAliveTimer.Elapsed += keepAliveTimer_Elapsed;
                _keepAliveTimer.Interval = 5 * 60 * 1000; // 5 minutes * 60s * 1000ms
                //_keepAliveTimer.Interval = 1000; // for testing
                _keepAliveTimer.AutoReset = true;
                _keepAliveTimer.Enabled   = true;
            }
            catch (Exception e)
            {
                Logger.Warn(e, "Connect to {0} on port {1} failed", _fisHostName, _fisPort);
                _tcpClient.Dispose();
                _tcpClient = null;
                throw; // re-throw
            }
        }
Beispiel #32
0
        public static void SendRaw(string Hostname, int TunnelPort, System.IO.Stream ClientStream)
        {
            System.Net.Sockets.TcpClient tunnelClient = new System.Net.Sockets.TcpClient(Hostname, TunnelPort);
            var tunnelStream     = tunnelClient.GetStream();
            var tunnelReadBuffer = new byte[BUFFER_SIZE];

            Task sendRelay    = new Task(() => StreamHelper.CopyTo(ClientStream, tunnelStream, BUFFER_SIZE));
            Task receiveRelay = new Task(() => StreamHelper.CopyTo(tunnelStream, ClientStream, BUFFER_SIZE));

            sendRelay.Start();
            receiveRelay.Start();

            Task.WaitAll(sendRelay, receiveRelay);

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

            if (tunnelClient != null)
            {
                tunnelClient.Close();
            }
        }
Beispiel #33
0
        /// <summary>
        /// 获取当前使用的IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalUsedIP()
        {
            string result = RunApp("route", "print", true);
            Match  m      = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");

            if (m.Success)
            {
                return(m.Groups[2].Value);
            }
            try
            {
                string ip;
                using (System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient())
                {
                    c.Connect("www.baidu.com", 80);
                    ip = ((IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                }
                return(ip);
            }
            catch (Exception)
            {
                return(null);
            }
        }
        /// <summary> Loop that waits for a connection and starts a ConnectionManager
        /// when it gets one.
        /// </summary>
        public override void  Run()
        {
            try
            {
                System.Net.Sockets.TcpListener temp_tcpListener;
                temp_tcpListener = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0], port);
                temp_tcpListener.Start();
                ss = temp_tcpListener;
                while (keepRunning())
                {
                    try
                    {
                        System.Net.Sockets.TcpClient newSocket = ss.AcceptTcpClient();
                        NuGenConnection conn = new NuGenConnection(parser, this.llp, newSocket);
                        newConnection(conn);
                    }
                    catch (System.IO.IOException)
                    {
                        //ignore - just timed out waiting for connection
                    }
                    catch (System.Exception)
                    {
                    }
                }

                ss.Stop();
            }
            catch (System.Exception)
            {
            }
            finally
            {
                //Bug 960113:  Make sure HL7Service.stop() is called to stop ConnectionCleaner thread.
                this.stop();
            }
        }
Beispiel #35
0
        } // End Sub Test1

        // https://stackoverflow.com/questions/28612289/tcpclient-connectasync-or-socket-beginconnect-with-non-blocking-timeout-setting
        public static void Test2()
        {
            IDnsSecResolver resolver = new DnsSecRecursiveDnsResolver();

            //using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient("example.com", 443))

            using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
            {
                System.Threading.Tasks.Task t = client.ConnectAsync("example.com", 443);
                t.Wait();

                using (ARSoft.Tools.Net.Net.DaneStream stream = new ARSoft.Tools.Net.Net.DaneStream(client.GetStream(), resolver))
                {
                    stream.AuthenticateAsClient("example.com", 443);

                    if (stream.IsAuthenticatedByDane)
                    {
                        System.Console.WriteLine("Stream is authenticated by DANE/TLSA");
                    }

                    // work with the stream
                } // End Using stream
            }     // End Using client
        }         // End Sub Test2
Beispiel #36
0
        public void Open()
        {
            if (cln != null)
            {
                Close(true);
            }

            if (string.IsNullOrEmpty(mAddress))
            {
                throw new MissingFieldException("Missing HostName");
            }

            cln = new System.Net.Sockets.TcpClient();
            Logger.LogMessage("OpenCom", "Open {0}", mAddress);
            ComLogger.Log("com", string.Format("Open {0} {1}", mAddress, GetResetDiagnosticString()));

            cln.Connect(IPHelper.Parse(mAddress));

            Stream cst = cln.GetStream();

            bwriter = new BinaryWriter(cst);
            sreader = new StreamReader(cst, Encoding.ASCII);
            swriter = new StreamWriter(cst, Encoding.ASCII);
        }
        protected override void Start()
        {
            base.Start();

            if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicName))
            {
                this.tcpClient = SIGVerseRosBridgeConnection.GetConnection(this.rosBridgeIP, this.sigverseBridgePort);

                RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicName, this.tcpClient);
            }
            else
            {
                this.tcpClient = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicName];
            }

            this.networkStream = this.tcpClient.GetStream();

            this.networkStream.ReadTimeout  = 100000;
            this.networkStream.WriteTimeout = 100000;

            this.laserScanMsg = new SIGVerseRosBridgeMessage <LaserScanForSIGVerseBridge>("publish", this.topicName, LaserScanForSIGVerseBridge.GetMessageType(), this.laserScan);

//			Debug.Log("this.layerMask.value = "+this.layerMask.value);
        }
Beispiel #38
0
        public static void Main(string[] args)
        {
            Console.Write("Please Enter Operation Mode <Client|Server>: ");
            string modeName = ConsoleReadLine();
            Guid   ChatServiceAnouncementType = Guid.Parse("b0021151-a1cc-4f82-aa8d-a2cdb905e6ca");

            if (modeName == "Server")
            {
                System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 28000));
                TL.Start();
                while (true)
                {
                    HandleConnection(modeName, ChatServiceAnouncementType, TL.AcceptTcpClient());
                }
            }
            if (modeName == "Client")
            {
                System.Net.Sockets.TcpClient TC = null;
                TC = new System.Net.Sockets.TcpClient();
                Console.Write("Please Enter Remote IP: ");
                TC.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ConsoleReadLine()), 28000));
                HandleConnection(modeName, ChatServiceAnouncementType, TC);
            }
        }
Beispiel #39
0
        public virtual void Close()
        {
            if (this.controlReader != null)
            {
                //              this.controlReader.Close();
                this.controlReader.Dispose();
                this.controlReader = null;
            }

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

            if (this.controlChannelReceiver != null)
            {
                this.controlChannelReceiver.Clear();
                this.controlChannelReceiver = null;
            }

            if (this.controlConnection != null)
            {
                try
                {
                    this.controlConnection.GetStream().Dispose();
                    this.controlConnection.Close();
                    this.controlConnection.Dispose();
                }
                catch (System.InvalidOperationException)
                {
                }
                this.controlConnection = null;
            }
        }
Beispiel #40
0
        static void Main(string[] args)
        {
            using var socket = new System.Net.Sockets.TcpClient("timo-linde.de", 25565);
            using var stream = socket.GetStream();

            stream.WriteObject(new Model.Handshake()
            {
                PacketId        = 0x00,
                NextState       = Model.HandshakeTargetState.Status,
                ProtocolVersion = 578,
                ServerAddress   = "timo-linde.de",
                ServerPort      = 25565,
            });

            stream.WriteObject(new Model.Request()
            {
                PacketId = 0x00,
            });

            var now = DateTimeOffset.Now.ToUnixTimeSeconds();

            stream.WriteObject(new Model.Ping()
            {
                PacketId = 0x01,
                Payload  = now
            });

            var response = stream.ReadObject <Model.Response>();
            var pong     = stream.ReadObject <Model.Pong>();

            Console.WriteLine(
                $"Payload sent: {now},\n" +
                $"Received:     {pong.Payload}"
                );
            Console.WriteLine(response.ResponseJson);
        }
Beispiel #41
0
        public void Open(System.Net.IPAddress Address, int Port)
        {
            if (this.p_IsOpened)
            {
                throw new FTPClientException("The connection is already opened.");
            }
            this.p_Address = Address;
            this.p_Port    = Port;

            try
            {
                this.controlConnection = new System.Net.Sockets.TcpClient(this.p_Address.ToString(), this.p_Port);
            }
            catch (System.Net.Sockets.SocketException e)
            {
                throw new FTPClientException("Error connecting to FTP server.", e);
            }
            this.controlWriter          = this.OpenWriter(this.controlConnection);
            this.controlChannelReceiver = new FTPControlChannelReceiver();
            this.controlChannelReceiver.ResponseReceived  += this.ControlChannelResponseReceived;
            this.controlChannelReceiver.ResponseCompleted += this.ControlChannelResponseCompleted;
            this.controlReader = this.OpenReader(this.controlConnection);
            this.AsyncControlReader(this.controlReader, this.controlChannelReceiver);
        }
Beispiel #42
0
        private static void HandleClient(object data)
        {
            try
            {
                System.Net.Sockets.TcpClient connection = (System.Net.Sockets.TcpClient)data;
                MainClass.DebugLog("Incoming connection from: " + connection.Client.RemoteEndPoint.ToString());
                Connections++;
                OpenConnections++;
                connection.NoDelay = true;
                System.Net.Sockets.NetworkStream ns     = connection.GetStream();
                System.IO.StreamReader           Reader = new System.IO.StreamReader(ns);
                string text;
                string timestamp = "";
                // give the user access to global cache
                // save the reference to global cache because we might need it in future
                System.IO.StreamWriter Writer = new System.IO.StreamWriter(ns);
                while (connection.Connected && !Reader.EndOfStream)
                {
                    text = Reader.ReadLine();
                    string        command    = text;
                    List <string> list       = new List <string>();
                    string        parameters = "";
                    if (command.Contains(" "))
                    {
                        parameters = command.Substring(command.IndexOf(" ") + 1);
                        command    = command.Substring(0, command.IndexOf(" "));
                        if (parameters.Contains(" "))
                        {
                            list.AddRange(parameters.Split(' '));
                        }
                    }

                    string project = null;
                    string section = null;
                    string l       = null;
                    string token   = null;
                    int    type    = 0;

                    switch (command.ToLower())
                    {
                    case "n":
                    case "s":
                    case "store":
                        if (Configuration.RequireAuth)
                        {
                            Writer.WriteLine("ERROR: you need to authenticate to log here");
                            Writer.Flush();
                            continue;
                        }
                        if (list.Count < 3)
                        {
                            Writer.WriteLine("ERROR: you are missing parameters for this command");
                            Writer.Flush();
                            continue;
                        }
                        project = list[0];
                        section = null;
                        if (project.Contains(":"))
                        {
                            section = project.Substring(project.IndexOf(":") + 1);
                            project = project.Substring(0, project.IndexOf(":"));
                            if (!Logger.ValidName(section))
                            {
                                Writer.WriteLine("ERROR: you provided invalid section name");
                                Writer.Flush();
                                continue;
                            }
                        }
                        if (!Logger.ValidName(project))
                        {
                            Writer.WriteLine("ERROR: you provided invalid section name");
                            Writer.Flush();
                            continue;
                        }

                        if (Auth.RequireLogin(project))
                        {
                            Writer.WriteLine("ERROR: you need to authenticate to log here");
                            Writer.Flush();
                            continue;
                        }

                        type = 0;
                        l    = text.Substring(list[0].Length + list[1].Length + command.Length + 3);

                        if (!int.TryParse(list[1], out type))
                        {
                            Writer.WriteLine("ERROR: you provided invalid log type");
                            Writer.Flush();
                            continue;
                        }

                        if (Logger.Write(l, project, section, type))
                        {
                            if (command != "n")
                            {
                                Writer.WriteLine("STORED");
                                Writer.Flush();
                            }
                            continue;
                        }

                        Writer.WriteLine("ERROR: internal error, check debug log");
                        Writer.Flush();
                        continue;

                    case "a":
                        if (list.Count < 4)
                        {
                            Writer.WriteLine("ERROR: you are missing parameters for this command");
                            Writer.Flush();
                            continue;
                        }
                        project = list[0];
                        section = null;
                        if (project.Contains(":"))
                        {
                            section = project.Substring(project.IndexOf(":") + 1);
                            project = project.Substring(0, project.IndexOf(":"));
                            if (!Logger.ValidName(section))
                            {
                                Writer.WriteLine("ERROR: you provided invalid section name");
                                Writer.Flush();
                                continue;
                            }
                        }
                        if (!Logger.ValidName(project))
                        {
                            Writer.WriteLine("ERROR: you provided invalid section name");
                            Writer.Flush();
                            continue;
                        }

                        token = list[2];

                        type = 0;
                        l    = text.Substring(list[0].Length + list[1].Length + command.Length + token.Length + 4);

                        if (!Auth.Login(project, token))
                        {
                            Writer.WriteLine("ERROR: you provided invalid token");
                            Writer.Flush();
                            continue;
                        }

                        if (!int.TryParse(list[1], out type))
                        {
                            Writer.WriteLine("ERROR: you provided invalid log type");
                            Writer.Flush();
                            continue;
                        }

                        if (Logger.Write(l, project, section, type))
                        {
                            if (command != "n")
                            {
                                Writer.WriteLine("STORED");
                                Writer.Flush();
                            }
                            continue;
                        }

                        Writer.WriteLine("ERROR: internal error, check debug log");
                        Writer.Flush();
                        continue;

                    case "quit":
                        connection.Close();
                        OpenConnections--;
                        return;
                    }
                    Writer.WriteLine("ERROR");
                    Writer.Flush();
                }
            } catch (Exception fail)
            {
                MainClass.exceptionHandler(fail);
            }
            OpenConnections--;
        }
Beispiel #43
0
 public LogonInfo(string userName, string id, System.Net.Sockets.TcpClient connection)
 {
     this.UserName   = userName;
     this.Id         = id;
     this.Connection = connection;
 }
Beispiel #44
0
        private void gSend_Click(object sender, EventArgs e)
        {
            if (gDesc.Text.Contains(defaultmsg) && gDesc.Text.Length - defaultmsg.Length < 3)
            {
                if (DialogResult.Yes == MessageBox.Show(
                        "You didn't provide a way for me to contact you!\n\n" +
                        "Wanna go back and add an email address or something?",
                        "No contact info ", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
                {
                    return;
                }
            }
            gExit.Enabled = gSend.Enabled = gDesc.Enabled = false;
            Application.DoEvents();
            try
            {
                gi.UserDescription = gDesc.Text;
                string serialized = gi.ToString();

                try
                {
                    serialized += "\r\n" + GeneralInfo.ser(LSSettings.singleton);
                }
                catch { serialized += "\r\n" + "LSSettings Serialization Error"; }

                try
                {
                    serialized += "\r\n" + GeneralInfo.ser(LSSettings.singleton.devs);
                }
                catch { serialized += "\r\n" + "LSDevices Serialization Error"; }



                byte[] payload = Z.lze(serialized, true);
                Int32  nix     = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                System.IO.File.WriteAllText("crash-" + nix, serialized, Encoding.UTF8);

                string hash;
                using (var sha = System.Security.Cryptography.MD5.Create())
                {
                    hash = BitConverter.ToString(sha.ComputeHash(
                                                     payload)).Replace("-", "").ToLower();
                }
                var ms = new System.IO.MemoryStream();



                /*
                 * POST /loopstream/report.php HTTP/1.1
                 * Host: ocv.me
                 * User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0
                 * Accept: text/html,application/xhtml+xml,application/xml;q=0.9,* /*;q=0.8
                 * Accept-Language: en-US,en;q=0.5
                 * Accept-Encoding: gzip, deflate
                 * Referer: http://ocv.me/loopstream/report.html
                 * Connection: keep-alive
                 * Cache-Control: max-age=0
                 * Content-Type: multipart/form-data; boundary=---------------------------145202957330368
                 * Content-Length: 11090
                 *
                 * -----------------------------145202957330368
                 * Content-Disposition: form-data; name="md"
                 *
                 * f25e056b844391cd9b6f787595c55768
                 * -----------------------------145202957330368
                 * Content-Disposition: form-data; name="se"; filename="dump.lzma"
                 * Content-Type: application/octet-stream
                 *
                 * FILEDATA...
                 * -----------------------------145202957330368--
                 */



                string boundary = DateTime.Now.Ticks.ToString("x").PadLeft(44, '-');
                string body     = string.Format(
                    "{1}{0}" +
                    "Content-Disposition: form-data; name=\"md\"{0}" +
                    "{0}{2}{0}{1}{0}" +
                    "Content-Disposition: form-data; name=\"se\"; filename=\"deadbeef.bin\"{0}" +
                    "Content-Type: application/octet-stream{0}" +
                    "{0}",
                    "\r\n",
                    boundary,
                    hash);

                Encoding enc = new UTF8Encoding(false);
                byte[]   buf = enc.GetBytes(body);
                ms.Write(buf, 0, buf.Length);
                ms.Write(payload, 0, payload.Length);
                buf = enc.GetBytes("\r\n" + boundary + "--\r\n");
                ms.Write(buf, 0, buf.Length);
                string header = string.Format(
                    "POST /loopstream/report.php HTTP/1.1{0}" +
                    "Host: ocv.me{0}" +
                    "User-Agent: Loopstream/{1}{0}" +
                    "Connection: close{0}" +
                    "Content-Type: multipart/form-data; boundary={2}{0}" +
                    "Content-Length: {3}{0}" +
                    "{0}",
                    "\r\n",
                    Application.ProductVersion,
                    boundary.Substring(2),
                    ms.Length);

                payload = ms.ToArray();
                buf     = enc.GetBytes(header);
                ms      = new System.IO.MemoryStream();
                ms.Write(buf, 0, buf.Length);
                ms.Write(payload, 0, payload.Length);
                ms.Seek(0, System.IO.SeekOrigin.Begin);

                System.Net.Sockets.TcpClient     tc;
                System.Net.Sockets.NetworkStream s;
                tc = new System.Net.Sockets.TcpClient();
                tc.Connect("ocv.me", 80);
                s = tc.GetStream();
                ms.WriteTo(s);
                s.Flush();
                buf = new byte[8192];
                int i = s.Read(buf, 0, buf.Length);
                header = enc.GetString(buf, 0, i);
                string msg = "";
                if (!header.Contains("ls_ex_rep_ok"))
                {
                    msg = "FAILED to send error info to devs!\n\n(the crash reporter just crashed)";
                }
                else
                {
                    msg = "Thank you !";
                }
                if (DialogResult.Yes == MessageBox.Show(
                        msg + "\n\n" + "Restart Loopstream?", "now what",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    Program.fixWorkingDirectory();
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("the crash reporter just crashed:\n\n" + ee.Message + "\n\n" + ee.StackTrace);
            }
            this.Close();
        }
Beispiel #45
0
 private static void Server_ClientConnected(object sender, System.Net.Sockets.TcpClient e)
 {
     Console.WriteLine("Client Connected.");
     System.Threading.Thread.Sleep(500);
 }
Beispiel #46
0
 private static void Server_ClientDisconnected(object sender, System.Net.Sockets.TcpClient e)
 {
     Console.WriteLine("Client Disconnected.");
 }
        /// <summary>
        /// Abrea a comunicação.
        /// </summary>
        /// <returns></returns>
        public override CommunicationResult Open()
        {
            CommunicationResult result = CommunicationResult.OpenFailed;

            try
            {
                lock (_tcpLock)
                {
                    LastError = CommunicationResult.Success;
                    if ((_tcpClient == null) || (_tcpClient.Client == null))
                    {
                        _tcpClient  = new System.Net.Sockets.TcpClient();
                        _receiving  = false;
                        _readResult = null;
                    }
                    AsyncCallback callback2 = null;
                    using (var resetEvent = new System.Threading.ManualResetEvent(false))
                    {
                        if (callback2 == null)
                        {
                            callback2 = delegate(IAsyncResult asyncResult) {
                                result = TryOpen(asyncResult);
                                try
                                {
                                    resetEvent.Set();
                                }
                                catch (NullReferenceException)
                                {
                                }
                                catch (ObjectDisposedException)
                                {
                                }
                            };
                        }
                        AsyncCallback requestCallback = callback2;
                        if ((_tcpClient == null) || (_tcpClient.Client == null))
                        {
                            return(CommunicationResult.OpenFailed);
                        }
                        _tcpClient.BeginConnect(RemoteEndPoint.Address, base.RemoteEndPoint.Port, requestCallback, _tcpClient);
                        if (!resetEvent.WaitOne(TcpTimeout, true))
                        {
                            try
                            {
                                _tcpClient.Close();
                            }
                            finally
                            {
                                result = CommunicationResult.OpenFailed;
                            }
                        }
                    }
                }
            }
            catch (ArgumentNullException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (ArgumentOutOfRangeException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (ObjectDisposedException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (System.Net.Sockets.SocketException exception)
            {
                if (exception.ErrorCode == 0x2748)
                {
                    result = CommunicationResult.AlreadyOpen;
                }
                else
                {
                    result = new CommunicationResult(exception.ErrorCode);
                }
            }
            catch (InvalidOperationException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (System.Security.SecurityException)
            {
                result = CommunicationResult.OpenFailed;
            }
            catch (System.Threading.AbandonedMutexException)
            {
                result = CommunicationResult.OpenFailed;
            }
            finally
            {
                if ((result.ErrorCode == 1) && !this.IsOpen)
                {
                    result = CommunicationResult.OpenFailed;
                }
                if ((result != 0) || (result.ErrorCode == 1))
                {
                    try
                    {
                        _tcpStream = _tcpClient.GetStream();
                        if (_tcpStream != null)
                        {
                            _tcpStream.WriteTimeout = TcpTimeout;
                            _tcpStream.ReadTimeout  = TcpTimeout;
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        result = CommunicationResult.Closed;
                    }
                    catch (InvalidOperationException)
                    {
                        result = CommunicationResult.Closed;
                    }
                }
                else
                {
                    _tcpClient = null;
                    HandleResult(result);
                }
            }
            return(result);
        }
Beispiel #48
0
        /// <summary>
        /// 受信コマンド解析
        /// </summary>
        /// <returns></returns>
        public string TCP_ReciveCommand()
        {
            if (null == objTCPSC)
            {
                return("");
            }

            System.Net.Sockets.TcpClient     objSck = objTCPSC.SckProperty;
            System.Net.Sockets.NetworkStream objStm = objTCPSC.MyProperty;
            string readStr = "";



            if (objStm != null && objSck != null)
            {
                // ソケット受信
                if (objSck.Available > 0 && objStm.DataAvailable)
                {
                    Byte[] dat = new Byte[objSck.Available];

                    if (0 == objStm.Read(dat, 0, dat.GetLength(0)))
                    {
                        // 切断を検知
                        objTCPSC.Dispose();
                        return("");
                    }

                    readStr      = System.Text.Encoding.GetEncoding("SHIFT-JIS").GetString(dat);
                    hwResiveStr += readStr;

                    {
                        string[] rsvCmd = readStr.Split('$');

                        for (int i = 0; i < rsvCmd.Length; i++)
                        {
                            if (rsvCmd[i].Length <= 3)
                            {
                                continue;
                            }

                            // ロータリーエンコーダから 速度を計算
                            if (rsvCmd[i].Substring(0, 3) == "A1,")
                            {
                                double   ResiveMS;
                                double   ResReR, ResReL;
                                string[] splStr = rsvCmd[i].Split(',');

                                if (splStr.Length < 4)
                                {
                                    continue;
                                }

                                // 0 A1
                                double.TryParse(splStr[1], out ResiveMS);      // 小数点付き 秒
                                double.TryParse(splStr[2], out ResReR);        // Right Wheel
                                double.TryParse(splStr[3], out ResReL);        // Left Wheel

#if !SPEED_FROM_TF
                                const double tireSize = VRSetting.TireSize;  // タイヤ直径 [mm]
                                const double OnePuls  = VRSetting.OnePulse;  // 一周のパルス数
                                {
                                    double SpeedSec = (double)System.Environment.TickCount / 1000.0;

                                    // 0.25秒以上の経過時間があれば計算 (あまりに瞬間的な値では把握しにくいため)
                                    if ((SpeedSec - oldSpeedSec) > 0.25)
                                    {
                                        // 速度計算(非動輪を基準)
                                        double wheelPulse = (Math.Abs(hwRErotR - oldWheelR) + Math.Abs(hwRErotL - oldWheelL)) * 0.5;
                                        double moveLength = (wheelPulse / OnePuls * (Math.PI * tireSize));

                                        nowSpeedMmSec = (double)moveLength / (SpeedSec - oldSpeedSec);
                                        nowLengthMm  += moveLength;

                                        oldSpeedSec = SpeedSec;
                                        oldWheelR   = hwRErotR;
                                        oldWheelL   = hwRErotL;

                                        SpeedUpdateCnt = 20;    // 速度情報 更新カウンタ (0になると古い情報として使わない)
                                    }
                                }
#endif
                                // 取得した差分を加算する
                                hwRErotR += ResReR;
                                hwRErotL += ResReL;



                                bhwRE = true;
                            }
                            else if (rsvCmd[i].Substring(0, 3) == "A2,")
                            {
                                // コンパス情報
                                // A2,22.5068,210$
                                double   ResiveMS;
                                int      ResiveCmp;
                                string[] splStr = rsvCmd[i].Split(',');

                                if (splStr.Length < 3)
                                {
                                    continue;
                                }

                                // splStr[0] "A2"
                                // ミリ秒取得
                                double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える
                                int.TryParse(splStr[2], out ResiveCmp);   // デジタルコンパス値
                                //hwCompass = ResiveCmp;
                                //bhwCompass = true;
                            }
                            else if (rsvCmd[i].Substring(0, 3) == "A3,")
                            {
                                // GPS情報
                                // $A3,38.266,36.8002,140.11559$
                                double   ResiveMS;
                                double   ResiveLandX; // 緯度
                                double   ResiveLandY; // 経度
                                string[] splStr = rsvCmd[i].Split(',');

                                // データが足らないことがある
                                if (splStr.Length < 4)
                                {
                                    continue;
                                }

                                // splStr[0] "A3"
                                // ミリ秒取得
                                double.TryParse(splStr[1], out ResiveMS);    // ms? 万ミリ秒に思える

                                double.TryParse(splStr[2], out ResiveLandX); // GPS値
                                double.TryParse(splStr[3], out ResiveLandY);
                                //bhwGPS = true;
                                //bhwUsbGPS = false;
                            }
                            else if (rsvCmd[i].Substring(0, 3) == "A4,")
                            {
                                // ロータリーエンコーダ  プロット座標
                                // 開始時 真北基準

                                /*
                                 * コマンド
                                 *  A4
                                 *  ↓
                                 *  戻り値
                                 *  A4,絶対座標X,絶対座標Y,絶対座標上での向きR$
                                 *
                                 *  絶対座標X[mm]
                                 *  絶対座標Y[mm]
                                 *  絶対座標上での向き[rad] -2π~2π
                                 *  浮動小数点です。
                                 */
                                double ResiveMS;
                                double ResiveX;
                                double ResiveY;
                                double ResiveRad;

                                string[] splStr = rsvCmd[i].Split(',');
                                if (splStr.Length < 5)
                                {
                                    continue;
                                }

                                // splStr[0] "A4"
                                // ミリ秒取得
                                double.TryParse(splStr[1], out ResiveMS);  // ms? 万ミリ秒に思える
                                double.TryParse(splStr[2], out ResiveX);   // ROS World座標X m
                                double.TryParse(splStr[3], out ResiveY);   // ROS World座標Y m
                                double.TryParse(splStr[4], out ResiveRad); // 向き -2PI 2PI

                                hwAMCL_X   = ResiveX;
                                hwAMCL_Y   = ResiveY;
                                hwAMCL_Ang = ResiveRad;

#if SPEED_FROM_TF
                                {
                                    double SpeedSec = (double)System.Environment.TickCount * 0.001; // / 1000.0;

                                    // 0.2秒以上の経過時間があれば計算 (あまりに瞬間的な値では把握しにくいため)
                                    //if ((SpeedSec - oldSpeedSec) > 0.2)
                                    if ((SpeedSec - oldSpeedSec) >= 0.5)
                                    {
                                        // 速度計算(非動輪を基準)
                                        double dx   = (hwAMCL_X * 1000.0) - (oldWheelR * 1000.0);
                                        double dy   = (hwAMCL_Y * 1000.0) - (oldWheelL * 1000.0);
                                        double dist = Math.Sqrt(dx * dx + dy * dy);

                                        nowSpeedMmSec = (double)(dist / (SpeedSec - oldSpeedSec));

                                        oldSpeedSec = SpeedSec;
                                        oldWheelR   = hwAMCL_X;
                                        oldWheelL   = hwAMCL_Y;

                                        SpeedUpdateCnt = 20;    // 速度情報 更新カウンタ (0になると古い情報として使わない)
                                    }
                                }
#endif

                                if (!bhwAMCL)
                                {
                                    // AMCL受信トリガ ON
                                    bhwTrgAMCL = true;
                                }
                                bhwAMCL = true;
                            }
                            else if (rsvCmd[i].Substring(0, 3) == "M0,")
                            {
                                // movebase情報
                                // M0, LinierX, LinierY, LinierZ, AngleX, AngleY, AngleZ $
                                double ResiveMS;

                                double   ResiveX;
                                double   ResiveY;
                                double   ResiveRad;
                                string[] splStr = rsvCmd[i].Split(',');

                                // splStr[0] "M0"
                                if (splStr.Length < 8)
                                {
                                    continue;
                                }


                                {
                                    // ミリ秒取得
                                    double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える

                                    double.TryParse(splStr[2], out ResiveX);  // ROS Linier X
                                    double.TryParse(splStr[3], out ResiveY);  // ROS Linier Y
                                    //double.TryParse(splStr[4], out ResiveX);  // ROS Linier Z
                                    //double.TryParse(splStr[5], out ResiveRad);  // Ros AnglerX
                                    //double.TryParse(splStr[6], out ResiveRad);  // Ros AnglerY
                                    double.TryParse(splStr[7], out ResiveRad);  // Ros AnglerZ

                                    hwMVBS_X   = ResiveX;
                                    hwMVBS_Y   = ResiveY;
                                    hwMVBS_Ang = ResiveRad;
                                }
                            }
                        }
                    }
                }
            }

            return(readStr);
        }
        void Start()
        {
            if (this.rosBridgeIP.Equals(string.Empty))
            {
                this.rosBridgeIP = ConfigManager.Instance.configInfo.rosbridgeIP;
            }
            if (this.sigverseBridgePort == 0)
            {
                this.sigverseBridgePort = ConfigManager.Instance.configInfo.sigverseBridgePort;
            }


            this.tcpClientCameraInfo = HSRCommon.GetSIGVerseRosbridgeConnection(this.rosBridgeIP, this.sigverseBridgePort);
            this.tcpClientImage      = HSRCommon.GetSIGVerseRosbridgeConnection(this.rosBridgeIP, this.sigverseBridgePort);

            this.networkStreamCameraInfo              = this.tcpClientCameraInfo.GetStream();
            this.networkStreamCameraInfo.ReadTimeout  = 100000;
            this.networkStreamCameraInfo.WriteTimeout = 100000;

            this.networkStreamImage              = this.tcpClientImage.GetStream();
            this.networkStreamImage.ReadTimeout  = 100000;
            this.networkStreamImage.WriteTimeout = 100000;

            // RGB Camera
            this.xtionRGBCamera = this.rgbCamera.GetComponentInChildren <Camera>();

            int imageWidth  = this.xtionRGBCamera.targetTexture.width;
            int imageHeight = this.xtionRGBCamera.targetTexture.height;

            this.imageTexture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGB24, false);


            //  [camera/rgb/CameraInfo]
            string distortionModel = "plumb_bob";

            double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 };
            double[] K = { 554, 0.0, 320, 0.0, 554, 240, 0.0, 0.0, 1.0 };
            double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };
            double[] P = { 554, 0.0, 320, 0.0, 0.0, 554, 240, 0.0, 0.0, 0.0, 1.0, 0.0 };

            //double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 };
            //double[] K = { 554.3827128226441, 0.0, 320.5, 0.0, 554.3827128226441, 240.5, 0.0, 0.0, 1.0 };
            //double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };
            //double[] P = { 554.3827128226441, 0.0, 320.5, 0.0, 0.0, 554.3827128226441, 240.5, 0.0, 0.0, 0.0, 1.0, 0.0 };

            RegionOfInterest roi = new RegionOfInterest(0, 0, 0, 0, false);

            this.cameraInfoData = new CameraInfoForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, distortionModel, D, K, R, P, 0, 0, roi);

            //  [camera/rgb/Image_raw]
            string encoding    = "rgb8";
            byte   isBigendian = 0;
            uint   step        = (uint)imageWidth * 3;

            this.imageData = new ImageForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, encoding, isBigendian, step, null);

            this.header = new Header(0, new SIGVerse.ROSBridge.msg_helpers.Time(0, 0), this.rgbCamera.name);


            this.cameraInfoMsg = new SIGVerseROSBridgeMessage <CameraInfoForSIGVerseBridge>("publish", this.topicNameCameraInfo, CameraInfoForSIGVerseBridge.GetMessageType(), this.cameraInfoData);
            this.imageMsg      = new SIGVerseROSBridgeMessage <ImageForSIGVerseBridge>     ("publish", this.topicNameImage, ImageForSIGVerseBridge.GetMessageType(), this.imageData);
        }
Beispiel #50
0
                private void StartScanBG()
                {
                    try
                    {
                        int hCount = 0;

                        foreach (string Host in Hosts)
                        {
                            if (BeginHostScanEvent != null)
                            {
                                BeginHostScanEvent(Host);
                            }

                            ScanHost sHost = new ScanHost(Host);
                            hCount++;

                            bool HostAlive = false;

                            HostAlive = IsHostAlive(Host);

                            if (HostAlive == false)
                            {
                                sHost.ClosedPorts.AddRange(Ports);
                                sHost.SetAllProtocols(false);
                            }
                            else
                            {
                                foreach (int Port in Ports)
                                {
                                    bool err = false;

                                    try
                                    {
                                        System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient(Host,
                                                                                                                  Port);

                                        err = false;
                                        sHost.OpenPorts.Add(Port);
                                    }
                                    catch (Exception)
                                    {
                                        err = true;
                                        sHost.ClosedPorts.Add(Port);
                                    }

                                    if (Port == ScanHost.SSHPort)
                                    {
                                        sHost.SSH = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.TelnetPort)
                                    {
                                        sHost.Telnet = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.HTTPPort)
                                    {
                                        sHost.HTTP = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.HTTPSPort)
                                    {
                                        sHost.HTTPS = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.RloginPort)
                                    {
                                        sHost.Rlogin = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.SerialPort)
                                    {
                                        sHost.Serial = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.RDPPort)
                                    {
                                        sHost.RDP = System.Convert.ToBoolean(!err);
                                    }
                                    else if (Port == ScanHost.VNCPort)
                                    {
                                        sHost.VNC = System.Convert.ToBoolean(!err);
                                    }
                                }
                            }

                            if (HostAlive == true)
                            {
                                try
                                {
                                    sHost.HostName = System.Net.Dns.GetHostEntry(sHost.HostIP).HostName;
                                }
                                catch (Exception)
                                {
                                }
                            }

                            _ScannedHosts.Add(sHost);
                            if (HostScannedEvent != null)
                            {
                                HostScannedEvent(sHost, hCount, Hosts.Count);
                            }
                        }

                        if (ScanCompleteEvent != null)
                        {
                            ScanCompleteEvent(_ScannedHosts);
                        }
                    }
                    catch (Exception ex)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg,
                                                            (string)
                                                            ("StartScanBG failed (Tools.PortScan)" + Constants.vbNewLine +
                                                             ex.Message), true);
                    }
                }
Beispiel #51
0
        public void ircthread()
        {
            int    port;
            string buf, nick, pw, server, chan, user, uname, msg, queueList;
            bool   flag = false;

            System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient();
            System.IO.TextReader         input;
            System.IO.TextWriter         output;

            nick   = "queueupchat";
            pw     = "oauth:mwhpwsgzsohz1ltvj9wtwnkwn0aqzq"; //oauth is password for IRC, Dont touch it
            server = "irc.twitch.tv";
            port   = 6667;
            chan   = "#" + textBox1.Text.ToLower();
            sock.Connect(server, port);

            input  = new System.IO.StreamReader(sock.GetStream());
            output = new System.IO.StreamWriter(sock.GetStream());

            //Starting USER and NICK login commands
            output.Write(
                "PASS " + pw + "\r\n" +
                "NICK " + nick + "\r\n" +
                "USER " + nick + " 8 * :" + nick + "\r\n" +  //this is
                "CAP REQ :twitch.tv/membership" + "\r\n " +  //the new magic
                "JOIN " + chan + "\r\n"                      //dont touch it
                                                             //EVER!

                );
            output.Flush();

            textBox2.Invoke((Action) delegate
            {
                textBox2.AppendText(DateTime.Now.ToShortTimeString() + "Connection Established \r\n\r\n"); //this should probably be in a try catch or something...
            });

            //Process each line received from irc server
            for (buf = input.ReadLine(); ; buf = input.ReadLine())
            {
                if (buf.Contains("PRIVMSG"))
                {
                    string[] split = buf.Split(new Char[] { ':' });   //all the shit for cutting up the raw IRC string into easily readable text
                    user = split[1];                                  //we need to edit this so if someone types sends a message with colons it doesnt split it again
                    string[] unamesplit = user.Split(new Char[] { '!' });
                    uname = unamesplit[0];
                    msg   = split[2];

                    if (msg.Equals("!join", StringComparison.Ordinal)) //cleaned up
                    {
                        flag = false;
                        queueGrid.Invoke((Action) delegate
                        {
                            for (int i = 0; i < count; i++)
                            {
                                if (nameList[i].twitchname.Equals(uname, StringComparison.Ordinal))
                                {
                                    output.Write("PRIVMSG " + chan + " :@" + uname + " You are already in queue\r\n");
                                    output.Flush(); //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag)
                            {
                                User newusr       = new User();
                                newusr.twitchname = uname;
                                nameList.Add(newusr);
                                queueGrid.DataSource = nameList;
                                count++;
                                output.Write("PRIVMSG " + chan + " :@" + uname + " Has successfully joined the queue!\r\n");
                                output.Flush(); //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                            }
                        });
                        flag = false;
                    }

                    if (msg.Equals("!leave", StringComparison.Ordinal)) //cleaned up
                    {
                        queueGrid.Invoke((Action) delegate
                        {
                            for (int i = 0; i < count; i++)
                            {
                                if (nameList[i].twitchname.Equals(uname, StringComparison.Ordinal))
                                {
                                    nameList.RemoveAt(i);
                                    count--;
                                    output.Write("PRIVMSG " + chan + " :@" + uname + " You have successfully left the queue!\r\n");
                                    output.Flush(); //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                                }
                            }
                        });
                    } // actually functioning now


                    string[] steamnamesplit = msg.Split(new Char[] { ' ' });
                    if (steamnamesplit[0].Equals("!steam", StringComparison.Ordinal))
                    {
                        flag = false;
                        queueGrid.Invoke((Action) delegate // checks if in the queue
                        {
                            for (int i = 0; i < count; i++)
                            {
                                if (nameList[i].twitchname.Equals(uname, StringComparison.Ordinal))
                                {
                                    try
                                    {
                                        nameList[i].steamname = steamnamesplit[1];
                                    }
                                    catch
                                    {
                                    }
                                    queueGrid.DataSource = blank;    // used to fix problem of names not appearing until another action occurs
                                    queueGrid.DataSource = nameList; // rebound to display all info
                                    output.Write("PRIVMSG " + chan + " :@" + uname + " Your steam name has been successfully updated!\r\n");
                                    output.Flush();                  //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                                    flag = true;
                                }
                            }
                        });

                        currGrid.Invoke((Action) delegate
                        {
                            for (int i = 0; i < groupcount; i++)
                            {
                                if (currentgroup[i].twitchname.Equals(uname, StringComparison.Ordinal))
                                {
                                    try
                                    {
                                        currentgroup[i].steamname = steamnamesplit[1];
                                    }
                                    catch
                                    {
                                    }
                                    queueGrid.DataSource = blank;    // used to fix problem of names not appearing until another action occurs
                                    queueGrid.DataSource = nameList; // rebound to display all info
                                    output.Write("PRIVMSG " + chan + " :@" + uname + " Your steam name has been successfully updated!\r\n");
                                    output.Flush();                  //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                                    flag = true;
                                }
                            }
                        });


                        if (!flag)
                        {
                            output.Write("PRIVMSG " + chan + " :@" + uname + " You can't add your steam name if you're not in the queue!\r\n");
                            output.Flush(); //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                        }
                        flag = false;
                    }

                    if (msg.Equals("!queue", StringComparison.Ordinal))
                    {
                        queueList = "";
                        foreach (User u in nameList)
                        {
                            queueList += " @" + u.twitchname + ",";
                        }
                        output.Write("PRIVMSG " + chan + " :CURRENT QUEUE: " + queueList + "\r\n");
                        output.Flush();
                    }

                    if (msg.Equals("!qhelp", StringComparison.Ordinal))
                    {
                        output.Write("PRIVMSG " + chan + " :@" + uname + " Command List: !join to join the queue, !leave to leave the queue, !steam 'steamname' to add your steam name, !queue to list the current queue of players\r\n");
                        output.Flush();         //does not work everytime, works 1st instance or if !queue is called but not others. LOW PRIORITY
                    } // actually functioning now


                    textBox2.Invoke((Action) delegate //puts the chat into the ircbox
                    {
                        //int s = textBox2.Text.Length - textBox2.Height;
                        //if (s < 0) s = 0;
                        //textBox2.Text = textBox2.Text.Substring(s);
                        //textBox2.Text += DateTime.Now.ToShortTimeString() + " " + uname + ": " + msg + "\r\n";
                        textBox2.AppendText(DateTime.Now.ToShortTimeString() + " " + uname + ": " + msg + "\r\n\r\n");
                        textBox2.Enabled       = false;
                        textBox2.WordWrap      = true;
                        textBox2.AcceptsReturn = true;
                    });

                    /*this.Invoke((Action)delegate
                     * {
                     *  this.TopMost = true;
                     *
                     * });*/
                }


                //Send pong reply to any ping messages to prevent timeouts (#JustIrcThings)
                if (buf.StartsWith("PING "))
                {
                    output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush();
                }
                if (buf[0] != ':')
                {
                    continue;
                }

                /* IRC commands come in one of these formats:
                 * :NICK!USER@HOST COMMAND ARGS ... :DATA\r\n
                 * :SERVER COMAND ARGS ... :DATA\r\n
                 */
            }
        }
Beispiel #52
0
        public static string GetRemoteIP(System.Net.Sockets.TcpClient cln)
        {
            string ip = cln.Client.RemoteEndPoint.ToString().Split(':')[0];

            return(ip);
        }
Beispiel #53
0
 public MessageConnection(System.Net.Sockets.TcpClient client, X509Certificate2 certificate)
     : base(client, certificate)
 {
     _ResponseReceivedQueue              = new ThreadedQueue(RemoteAddress + ":" + RemotePort, TimeSpan.FromSeconds(20));
     _ResponseReceivedQueue.receiveNext += ProcessResponse;
 }
        public void Initialize(string rosBridgeIP, int sigverseBridgePort, string topicNameCameraInfo, string topicNameImage, bool isUsingThread)
        {
            if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicNameCameraInfo))
            {
                this.tcpClientCameraInfo = SIGVerseRosBridgeConnection.GetConnection(rosBridgeIP, sigverseBridgePort);

                RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicNameCameraInfo, this.tcpClientCameraInfo);
            }
            else
            {
                this.tcpClientCameraInfo = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicNameCameraInfo];
            }

            if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicNameImage))
            {
                this.tcpClientImage = SIGVerseRosBridgeConnection.GetConnection(rosBridgeIP, sigverseBridgePort);

                RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicNameImage, this.tcpClientImage);
            }
            else
            {
                this.tcpClientImage = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicNameImage];
            }

            this.networkStreamCameraInfo              = this.tcpClientCameraInfo.GetStream();
            this.networkStreamCameraInfo.ReadTimeout  = 100000;
            this.networkStreamCameraInfo.WriteTimeout = 100000;

            this.networkStreamImage              = this.tcpClientImage.GetStream();
            this.networkStreamImage.ReadTimeout  = 100000;
            this.networkStreamImage.WriteTimeout = 100000;


            // Depth Camera
            this.depthCamera = this.cameraFrameObj.GetComponentInChildren <Camera>();

            int imageWidth  = this.depthCamera.targetTexture.width;
            int imageHeight = this.depthCamera.targetTexture.height;

            this.byteArray = new byte[imageWidth * imageHeight * 2];

            for (int i = 0; i < this.byteArray.Length; i++)
            {
                this.byteArray[i] = 0;
            }

            this.imageTexture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGB24, false);


            //  [camera/depth/CameraInfo]
            string distortionModel = "plumb_bob";

            double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 };
            double[] K = { 465, 0.0, 320, 0.0, 465, 240, 0.0, 0.0, 1.0 };
            double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };
            double[] P = { 465, 0.0, 320, 0.0, 0.0, 465, 240, 0.0, 0.0, 0.0, 1.0, 0.0 };

//			double[] D = { 0.14078746736049652, 0.07252906262874603, 0.004671256057918072, 0.0014421826926991343, 0.06731976568698883 };
//			double[] K = { 475.25030517578125, 0.0, 333.3515625, 0.0, 475.2502136230469, 245.8830108642578, 0.0, 0.0, 1.0 };
//			double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };
//			double[] P = { 475.25030517578125, 0.0, 333.3515625, 0.024700000882148743, 0.0, 475.2502136230469, 245.8830108642578, -0.0007332635577768087, 0.0, 0.0, 1.0, 0.004069563001394272 };

            RegionOfInterest roi = new RegionOfInterest(0, 0, 0, 0, false);

            this.cameraInfoData = new CameraInfoForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, distortionModel, D, K, R, P, 0, 0, roi);

            //  [camera/depth/Image_raw]
            string encoding    = "16UC1";
            byte   isBigendian = 0;
            uint   step        = (uint)imageWidth * 2;

            this.imageData = new ImageForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, encoding, isBigendian, step, null);

            this.header = new Header(0, new SIGVerse.RosBridge.msg_helpers.Time(0, 0), this.cameraFrameObj.name);

            this.cameraInfoMsg = new SIGVerseRosBridgeMessage <CameraInfoForSIGVerseBridge>("publish", topicNameCameraInfo, CameraInfoForSIGVerseBridge.GetMessageType(), this.cameraInfoData);
            this.imageMsg      = new SIGVerseRosBridgeMessage <ImageForSIGVerseBridge>     ("publish", topicNameImage, ImageForSIGVerseBridge.GetMessageType(), this.imageData);

            this.isUsingThread = isUsingThread;
        }
Beispiel #55
0
        static void Main(string[] args)
        {
            //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 =
                new System.Net.Sockets.TcpListener(ipAdd, port);

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

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("クライアント({0}:{1})と接続しました。",
                              ((System.Net.IPEndPoint)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;
                    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');
            resMsg = resMsg.TrimEnd('\r');
            Console.WriteLine(resMsg);

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

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

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

            Console.ReadLine();
        }
Beispiel #56
0
        private void Main()
        {
            using (Connection = new System.Net.Sockets.TcpClient())
            {
                try
                {
                    Connection.Connect(Server.Address, Server.Port);
                    Blowfish = new Library.BlowfishEngine(Server.Token);
                    State    = State.Load;

                    BinaryReader br = new BinaryReader(Connection.GetStream());
                    for (int n = 0; State == State.Load; n++)
                    {
                        int    size   = br.ReadInt16();
                        byte[] buffer = br.ReadBytes(size - 2);

                        if (size > 2)
                        {
                            if (n > 0)                             //ToDo encrypt = true, false
                            {
                                buffer = Blowfish.Decrypt(buffer);
                            }

                            Logger.Trace("Server packet: " + Packet.Utils.prettyHex(buffer));

                            switch (buffer[0])
                            {
                            case 0x00:
                                _onInit(buffer);
                                break;

                            case 0x01:
                                _onLoginFail(buffer);
                                State = State.Init;
                                break;

                            case 0x03:
                                _onLoginOk(buffer);
                                break;

                            case 0x04:
                                _onServerList(buffer);
                                break;

                            case 0x06:
                                _onPlayFail(buffer);
                                State = State.Init;
                                break;

                            case 0x07:
                                _onPlayOk(buffer);
                                State = State.Last;
                                break;

                            case 0x0B:
                                //gameguard check verified from server
                                _onGameGuardReply(buffer);
                                break;
                            }
                        }
                        else if (size < 2)
                        {
                            throw new EndOfStreamException();
                        }
                    }

                    if (State == State.Last)
                    {
                        if (ServerSelected != null)
                        {
                            ServerSelected(LoginKey, GameKey);
                        }
                    }
                    else
                    {
                        Logger.Fatal("State fail");
                    }
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    Logger.Error(e.Message);
                }
                catch (Exception e)
                {
                    Logger.Fatal(e.ToString());
                }
                finally
                {
                    Connection.Close();
                }
            }
        }
Beispiel #57
0
        private void StartupEndpoint()
        {
            var config = new SetupConfig();

            try
            {
                LoggerCQ.LogInfo("Attempting to upgrade database.");
                var connectionStringSettings = ConfigurationManager.ConnectionStrings["DatastoreEntities"];
                var connectionStringBuilder  = new SqlConnectionStringBuilder(connectionStringSettings.ConnectionString)
                {
                    InitialCatalog = "Master"
                };

                //Make sure there are no other nHydrate installations on this database
                if (DbMaintenanceHelper.ContainsOtherInstalls(connectionStringSettings.ConnectionString))
                {
                    LoggerCQ.LogError($"The database contains another installation. This is an error condition. Database={connectionStringBuilder.InitialCatalog}");
                    throw new Exception($"The database contains another installation. This is an error condition. Database={connectionStringBuilder.InitialCatalog}");
                }

                //Even a blank database gets updated below so save if DB is blank when started
                var isBlank = DbMaintenanceHelper.IsBlank(connectionStringSettings.ConnectionString);

                var installer = new DatabaseInstaller();
                if (installer.NeedsUpdate(connectionStringSettings.ConnectionString))
                {
                    var setup = new InstallSetup
                    {
                        AcceptVersionWarningsChangedScripts = true,
                        AcceptVersionWarningsNewScripts     = true,
                        ConnectionString       = connectionStringSettings.ConnectionString,
                        InstallStatus          = InstallStatusConstants.Upgrade,
                        MasterConnectionString = connectionStringBuilder.ToString(),
                        SuppressUI             = true,
                    };
                    installer.Install(setup);
                }

                //If new database then add file split data files to reduce file locking
                if (isBlank)
                {
                    try
                    {
                        DbMaintenanceHelper.SplitDbFiles(connectionStringSettings.ConnectionString);
                        LoggerCQ.LogInfo("New database has split data files.");
                    }
                    catch
                    {
                        LoggerCQ.LogWarning("New database could not split data files.");
                    }

                    try
                    {
                        var configFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "setup.config");
                        if (File.Exists(configFile))
                        {
                            var barr = File.ReadAllBytes(configFile);
                            config = ServerUtilities.DeserializeObject <SetupConfig>(barr);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception($"Setup configuration file is not valid.");
                    }

                    if (config != null)
                    {
                        if (!string.IsNullOrEmpty(config.ListDataPath) && !Directory.Exists(config.ListDataPath))
                        {
                            throw new Exception("The setup configuration file value 'ListDataPath' is not valid");
                        }
                        if (!string.IsNullOrEmpty(config.IndexPath) && !Directory.Exists(config.IndexPath))
                        {
                            throw new Exception("The setup configuration file value 'IndexPath' is not valid");
                        }

                        //Create a file group for List tables
                        config.ListDataPath = DbMaintenanceHelper.CreateFileGroup(connectionStringSettings.ConnectionString, config.ListDataPath, SetupConfig.YFileGroup);

                        //Create a file group for Indexes
                        config.IndexPath = DbMaintenanceHelper.CreateFileGroup(connectionStringSettings.ConnectionString, config.IndexPath, SetupConfig.IndexFileGroup);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerCQ.LogError(ex, "Failed on database upgrade.");
                throw new Exception("Failed on database upgrade.");
            }

            LoggerCQ.LogInfo("Service started begin");
            try
            {
                #region Primary Endpoint

                var service = new Gravitybox.Datastore.Server.Core.SystemCore(ConfigurationManager.ConnectionStrings["DatastoreEntities"].ConnectionString, _enableHouseKeeping);
                if (config != null)
                {
                    ConfigHelper.SetupConfig = config;
                }

                #region Determine if configured port is free
                var isPortFree = false;
                do
                {
                    try
                    {
                        //Determine if can connect to port
                        using (var p1 = new System.Net.Sockets.TcpClient("localhost", ConfigHelper.Port))
                        {
                        }
                        //If did connect successfully then there is already something on this port
                        isPortFree = false;
                        LoggerCQ.LogInfo($"Port {ConfigHelper.Port} is in use...");
                        System.Threading.Thread.Sleep(3000); //wait...
                    }
                    catch (Exception ex)
                    {
                        //If there is an error connecting then nothing is listening on that port so FREE
                        isPortFree = true;
                    }
                } while (!isPortFree);
                #endregion

                var primaryAddress = new Uri($"net.tcp://localhost:{ConfigHelper.Port}/__datastore_core");
                var primaryHost    = new ServiceHost(service, primaryAddress);

                //Initialize the service
                var netTcpBinding = new NetTcpBinding();
                netTcpBinding.MaxConnections = ThrottleMax;
                netTcpBinding.Security.Mode  = SecurityMode.None;
                primaryHost.AddServiceEndpoint(typeof(Gravitybox.Datastore.Common.ISystemCore), netTcpBinding, string.Empty);

                //Add more threads
                var stb = new ServiceThrottlingBehavior
                {
                    MaxConcurrentSessions  = ThrottleMax,
                    MaxConcurrentCalls     = ThrottleMax,
                    MaxConcurrentInstances = ThrottleMax,
                };
                primaryHost.Description.Behaviors.Add(stb);

                primaryHost.Open();

                //Create Core Listener
                var primaryEndpoint = new EndpointAddress(primaryHost.BaseAddresses.First().AbsoluteUri);
                var primaryClient   = new ChannelFactory <Gravitybox.Datastore.Common.ISystemCore>(netTcpBinding, primaryEndpoint);
                _core = primaryClient.CreateChannel();
                (_core as IContextChannel).OperationTimeout = new TimeSpan(0, 0, 120); //Timeout=2m

                #endregion

                LoadEngine(service);
                service.Manager.ResetMaster();
                LoggerCQ.LogInfo("Service started complete");
                ConfigHelper.StartUp();
            }
            catch (Exception ex)
            {
                LoggerCQ.LogError(ex);
                throw;
            }
        }
Beispiel #58
0
 internal bool Send(System.Net.Sockets.TcpClient tcpclient)
 {
     return(this.Send(tcpclient, 0));
 }
Beispiel #59
0
 public TcpSocket(string ipAddress, int port)
 {
     _tcpClient = new System.Net.Sockets.TcpClient(ipAddress, port);
 }
Beispiel #60
-1
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="clientId">Client Id</param>
 /// <param name="client">TcpClient instance for the client</param>
 /// <param name="serverIP">Server's IP</param>
 public TcpClientManager(int clientId, System.Net.Sockets.TcpClient client, String serverIP)
 {
     this._clientId = clientId;
     this._tcpClient = client;
     this.BeginReadFromClient();
     this.serverIP = serverIP;
 }