Esempio n. 1
0
        private static void RegisterOnMasterServer(NetWorker networker, int maxPlayers, string masterServerHost, ushort masterServerPort)
        {
            // The Master Server communicates over TCP
            TCPClient client = new TCPClient();

            // Once this client has been accepted by the master server it should send it's get request
            client.serverAccepted += (sender) =>
            {
                try
                {
                    Console.WriteLine("\nAccepted On Master Server");
                    // Create the get request with the desired filters
                    JSONNode  sendData     = JSONNode.Parse("{}");
                    JSONClass registerData = new JSONClass();
                    registerData.Add("id", "myGame");
                    registerData.Add("name", "Forge Game");
                    registerData.Add("port", new JSONData(networker.Port));
                    registerData.Add("playerCount", new JSONData(0));
                    registerData.Add("maxPlayers", new JSONData(maxPlayers));
                    registerData.Add("comment", "Demo comment...");
                    registerData.Add("type", "Deathmatch");
                    registerData.Add("mode", "Teams");
                    registerData.Add("protocol", networker is BaseUDP ? "udp" : "tcp");

                    sendData.Add("register", registerData);

                    BeardedManStudios.Forge.Networking.Frame.Text temp = BeardedManStudios.Forge.Networking.Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_REGISTER, true);

                    // Send the request to the server
                    client.Send(temp);
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;
                }
            };

            client.Connect(masterServerHost, masterServerPort);

            client.disconnected += (sender) =>
            {
                client.Disconnect(false);
                Console.WriteLine("Master server disconnected");
            };
            //Networker.disconnected += () =>
            //{
            //	client.Disconnect(false);
            //	MasterServerNetworker = null;
            //};
        }
    public override void OnInspectorGUI()
    {
        client      = (TCPClient)target;
        client.host = EditorGUILayout.TextField("Host: ", client.host);
        client.port = EditorGUILayout.IntField("Port: ", client.port);

        client.message = EditorGUILayout.TextField("Message: ", client.message);
        client.msgType = EditorGUILayout.TextField("Message Type: ", client.msgType);

        EditorGUILayout.Space();
        SerializedProperty pcdWriter = serializedObject.FindProperty("pcdWriter");

        EditorGUILayout.PropertyField(pcdWriter, new GUIContent("PCDWriter"), true);
        serializedObject.ApplyModifiedProperties();

        if (GUILayout.Button("Connect to server"))
        {
            client.ConnectToServerAsync();
        }

        if (GUILayout.Button("Send message"))
        {
            client.SendMessageToNet(client.message, client.msgType);
        }

        if (GUILayout.Button("Send PCD"))
        {
            client.SendPointCloud();
        }

        if (GUILayout.Button("Disconnect"))
        {
            client.Disconnect();
        }
    }
Esempio n. 3
0
        private void InitializeTcpClient()
        {
            var callback = new ChatCallback
            {
                OnConnected = () =>
                              Dispatcher.Invoke(() => PrintMessage("Pomyślnie połączono z " + IpAddress + ":" + Port)),
                OnMessageReceived = message => Dispatcher.Invoke(() =>
                {
                    var format = MessageExtractor.Extract(message);
                    if (format == string.Empty)
                    {
                        return;
                    }

                    var msg = InformationConverter.Deserialize(format);
                    if (mutedUsers.Contains(msg.Nick))
                    {
                        return;
                    }

                    switch (msg.Type)
                    {
                    case InformationType.Message:
                        PrintUserLine(msg.Nick, msg.Message);
                        break;

                    case InformationType.Voice:
                        {
                            if (!UsersSpeakingTextBlock.Text.Contains(msg.Nick))
                            {
                                UsersSpeakingTextBlock.Text += "\uD83D\uDD0A" + msg.Nick + Environment.NewLine;
                            }
                            var byteMessage = Convert.FromBase64String(msg.Message);
                            _audioManager.Play(byteMessage);
                            break;
                        }

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }),
                OnDisconnected = () => Dispatcher.Invoke(() =>
                {
                    _client.Disconnect();
                    Environment.Exit(0);
                }),
                OnCannotConnect = () => Dispatcher.Invoke(() =>
                {
                    var formattedMessage = new ColoredMessageBuilder()
                                           .With("Nie można połączyć się z serwerem. Sprawdź dane połączenia.")
                                           .Build();
                    ChatBlock.Document.Blocks.Add(formattedMessage);
                    ShowConnectionDialog();
                    ConnectToServer();
                })
            };

            _client = new TCPClient(callback);
            ConnectToServer();
        }
Esempio n. 4
0
        private void btncnt_Clicked(object sender, EventArgs e)
        {
            t?.Abort();
            switch (btncnt.Text)
            {
            case "Connect":
                client      = new TCPClient(ip.Text, ushort.Parse(port.Text));
                btncnt.Text = "Disconnect";
                smsg.Text   = "";
                try
                {
                    try { client.Connect(); } catch (Exception ex) { smsg.Text = ex.Message; }
                    Thread.Sleep(500);
                    if (client.Connected)
                    {
                        t = new Thread(new ThreadStart(ListenToServer));
                        t.Start();
                    }
                }
                catch { smsg.Text = "Connection Refused!"; btncnt.Text = "Connect"; }
                break;

            case "Disconnect":
                btncnt.Text = "Connect";
                t.Abort();
                client.SendString("ClientDisconnected-ID:" + id);
                client.Disconnect();
                break;
            }
        }
Esempio n. 5
0
 public void SendThread(object obj)
 {
     byte[] magic = System.BitConverter.GetBytes(MAGIC_NUMBER);
     while (true)
     {
         try
         {
             if (ServerSetting.ReporterIP != null)
             {
                 if (m_ErrList.HasItem())
                 {
                     string    str = m_ErrList.GetItem();
                     TCPClient tt  = new TCPClient(null);
                     if (tt.Connect(ServerSetting.ReporterIP, ServerSetting.ReporterPort, 0, 0, false))
                     {
                         byte[] txt      = System.Text.Encoding.ASCII.GetBytes(str);
                         byte[] size     = System.BitConverter.GetBytes((ushort)txt.Length);
                         byte[] sendData = new byte[txt.Length + 6];
                         System.Array.Copy(txt, 0, sendData, 6, txt.Length);
                         System.Array.Copy(size, 0, sendData, 4, size.Length);
                         System.Array.Copy(magic, 0, sendData, 0, magic.Length);
                         tt.Send(sendData);
                         tt.Disconnect();
                     }
                 }
             }
         }
         catch
         {
         }
         Thread.Sleep(500);
     }
 }
Esempio n. 6
0
        private void RefreshMasterServerListings()
        {
            masterClient = new TCPMasterClient();

            masterClient.serverAccepted += (sender) =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", Settings.serverId);
                    getData.Add("type", Settings.type);
                    getData.Add("mode", Settings.mode);

                    sendData.Add("get", getData);

                    // Send the request to the server
                    masterClient.Send(TextFrame.CreateFromString(masterClient.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    masterClient.Disconnect(true);
                    masterClient = null;
                }
            };

            masterClient.textMessageReceived += (player, frame, sender) =>
            {
                try
                {
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    if (data["hosts"] != null)
                    {
                        var response = new MasterServerResponse(data["hosts"].AsArray);

                        if (response != null && response.serverResponse.Count > 0)
                        {
                            // Go through all of the available hosts and add them to the server browser
                            foreach (var server in response.serverResponse)
                            {
                                // Run on main thread as we are creating UnityEngine.GameObjects
                                MainThreadManager.Run(() => AddServer(server.Address, server.Port));
                            }
                        }
                    }
                } finally
                {
                    if (masterClient != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        masterClient.Disconnect(true);
                        masterClient = null;
                    }
                }
            };

            masterClient.Connect(Settings.masterServerHost, Settings.masterServerPort);
        }
Esempio n. 7
0
        public void Disconnect()
        {
            if (peerId == 0)
            {
                this.Warn("not conect yet");
                return;
            }

            if (!Connected)
            {
                return;
            }

            cli.Disconnect(peerId);
        }
Esempio n. 8
0
        private void connectRAButton_Click(object sender, EventArgs e)
        {
            if ((ServerType)Settings.Default.ServerType == ServerType.Local)
            {
                MessageBoxEx.Show(this, "RA is not enabled!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            TCPClient client = (TCPClient)TCManager.Instance.RAClient;

            if (client != null)
            {
                client.Disconnect();
            }

            ConnectRA();
        }
Esempio n. 9
0
 public void DisconnectFromHost()
 {
     if (_tcpClient.IsConnected)
     {
         WriteLog("DisconnectFromHost");
         TCPClientDataSend(new PUserLogout
         {
             SessionToken = _sessionToken
         });
         _sessionToken = 0;
         IsMapLoaded   = false;
         _myPlayerData = null;
         if (_tcpClient != null)
         {
             _tcpClient.Disconnect();
         }
     }
     else
     {
         WriteLog("!DisconnectFromHost");
     }
 }
Esempio n. 10
0
        public void Refresh()
        {
            // Clear out all the currently listed servers
            for (int i = content.childCount - 1; i >= 0; --i)
            {
                Destroy(content.GetChild(i).gameObject);
            }

            // The Master Server communicates over TCP
            client = new TCPMasterClient();

            // Once this client has been accepted by the master server it should sent it's get request
            client.serverAccepted += (sender) =>
            {
                try
                {
                    // Create the get request with the desired filters
                    JSONNode  sendData = JSONNode.Parse("{}");
                    JSONClass getData  = new JSONClass();
                    getData.Add("id", gameId);
                    getData.Add("type", gameType);
                    getData.Add("mode", gameMode);

                    sendData.Add("get", getData);

                    // Send the request to the server
                    client.Send(Frame.Text.CreateFromString(client.Time.Timestep, sendData.ToString(), true, Receivers.Server, MessageGroupIds.MASTER_SERVER_GET, true));
                }
                catch
                {
                    // If anything fails, then this client needs to be disconnected
                    client.Disconnect(true);
                    client = null;
                }
            };

            // An event that is raised when the server responds with hosts
            client.textMessageReceived += (player, frame, sender) =>
            {
                try
                {
                    // Get the list of hosts to iterate through from the frame payload
                    JSONNode data = JSONNode.Parse(frame.ToString());
                    if (data["hosts"] != null)
                    {
                        MasterServerResponse response = new MasterServerResponse(data["hosts"].AsArray);

                        if (response != null && response.serverResponse.Count > 0)
                        {
                            // Go through all of the available hosts and add them to the server browser
                            foreach (MasterServerResponse.Server server in response.serverResponse)
                            {
                                string protocol = server.Protocol;
                                string address  = server.Address;
                                ushort port     = server.Port;
                                string name     = server.Name;

                                // name, address, port, comment, type, mode, players, maxPlayers, protocol
                                CreateServerOption(name, () =>
                                {
                                    // Determine which protocol should be used when this client connects
                                    NetWorker socket = null;

                                    if (protocol == "udp")
                                    {
                                        socket = new UDPClient();
                                        ((UDPClient)socket).Connect(address, port, natServerHost, natServerPort);
                                    }
                                    else if (protocol == "tcp")
                                    {
                                        socket = new TCPClient();
                                        ((TCPClient)socket).Connect(address, port);
                                    }
#if !UNITY_IOS && !UNITY_ANDROID
                                    else if (protocol == "web")
                                    {
                                        socket = new TCPClientWebsockets();
                                        ((TCPClientWebsockets)socket).Connect(address, port);
                                    }
#endif
                                    if (socket == null)
                                    {
                                        throw new Exception("No socket of type " + protocol + " could be established");
                                    }

                                    Connected(socket);
                                });
                            }
                        }
                    }
                }
                finally
                {
                    if (client != null)
                    {
                        // If we succeed or fail the client needs to disconnect from the Master Server
                        client.Disconnect(true);
                        client = null;
                    }
                }
            };

            client.Connect(masterServerHost, (ushort)masterServerPort);
        }
Esempio n. 11
0
 public void Disconnect()
 {
     _client.Disconnect();
 }
Esempio n. 12
0
 public void Disconnect()
 {
     client.Disconnect();
     connected = false;
 }
Esempio n. 13
0
 public void Disconnect()
 {
     ActiveDisconnect = true;
     _tcpClient.Disconnect();
 }
Esempio n. 14
0
		public async void TCPTryDisconnect()
		{
			tcpClient.Disconnect();
		}
Esempio n. 15
0
 void SendPackage(TCPClient client, TcpPackage package)
 {
     try
     {
         client.SendPackage(package);
     }
     catch { Log($"Error sending package to client {{Host: {client.Ip} Port: {client.Port}}}"); client.Disconnect(); }
 }