public void Connect() { Debug.Log("CONNECT"); if (connectUsingMatchmaking) { ConnectToMatchmaking(); return; } ushort port; if (!ushort.TryParse(portNumber.text, out port)) { Debug.LogError("The supplied port number is not within the allowed range 0-" + ushort.MaxValue); return; } NetWorker client; if (useTCP) { client = new TCPClient(); Debug.Log($"Connecting to: {ipAddress.text.Trim()} port {port}"); ((TCPClient)client).Connect(ipAddress.text.Trim(), (ushort)port); } else { client = new UDPClient(); Debug.Log($"Connecting to: {ipAddress.text.Trim()} port {port}"); if (natServerHost.Trim().Length == 0) { ((UDPClient)client).Connect(ipAddress.text.Trim(), (ushort)port); } else { ((UDPClient)client).Connect(ipAddress.text.Trim(), (ushort)port, natServerHost, natServerPort); } } Connected(client); }
public void ConnectToMatchmaking() { if (_matchmaking) { return; } SetToggledButtons(false); _matchmaking = true; if (mgr == null && networkManager == null) { Debug.LogWarning("A network manager was not provided, generating a new one instead"); networkManager = new GameObject("Network Manager"); mgr = networkManager.AddComponent <NetworkManager>(); } else if (mgr == null) { mgr = Instantiate(networkManager).GetComponent <NetworkManager>(); } mgr.MatchmakingServersFromMasterServer(masterServerHost, masterServerPort, myElo, (response) => { _matchmaking = false; SetToggledButtons(true); Debug.LogFormat("Matching Server(s) count[{0}]", response.serverResponse.Count); //TODO: YOUR OWN MATCHMAKING EXTRA LOGIC HERE! // I just make it randomly pick a server... you can do whatever you please! if (response != null && response.serverResponse.Count > 0) { MasterServerResponse.Server server = response.serverResponse[Random.Range(0, response.serverResponse.Count)]; //TCPClient client = new TCPClient(); UDPClient client = new UDPClient(); client.Connect(server.Address, server.Port); Connected(client); } }); }
/// <summary> /// Connect to the NAT hole punch server, this is called from a client machine /// </summary> /// <param name="host">The host address of the server the client is trying to connect to</param> /// <param name="port">The port number of the server the client is trying to connect to</param> /// <param name="clientPort">The port number that the client is listening on</param> /// <param name="natServer">The NAT server host address to connect to</param> /// <param name="natPort">The NAT server port number to connect to</param> public void Connect(string host, ushort port, ushort clientPort, string natServer, ushort natPort = DEFAULT_NAT_SERVER_PORT) { // Don't allow multiple NAT server connection requests at once if (Client != null) return; // Connect to the NAT server Client = new UDPClient(); Client.Connect(natServer, natPort, pendCreates: true); Debug.Log("Connecting to nat server"); NetWorker.BaseNetworkEvent accepted = (NetWorker sender) => { // Send the data to the nat server with the host address and port that this client // is trying to connect to so that it can punch a hole in the network for this client JSONNode sendJson = JSONNode.Parse("{}"); sendJson.Add("host", new JSONData(host)); sendJson.Add("port", new JSONData(port)); sendJson.Add("clientPort", new JSONData(clientPort)); // Send the message to the NAT server Text connect = Text.CreateFromString(Client.Time.Timestep, sendJson.ToString(), false, Receivers.Server, MessageGroupIds.NAT_SERVER_CONNECT, false); Client.Send(connect, true); Debug.Log("Connected to NAT server and sent info for NAT punching"); Client.messageConfirmed += (player, packet) => { if (packet.uniqueId == connect.UniqueId) { Client.Disconnect(false); Debug.Log("Disconnecting from NAT server"); } }; }; Client.serverAccepted += accepted; }
public virtual void StartAsClient(Scene pScene, NetworkSceneManagerSetting pSettings) { _settings = pSettings; SceneManager.MoveGameObjectToScene(gameObject, pScene); Disconnect(); InitializeDefaults(); NetWorker client; if (_settings.UseTCP) { client = new TCPClient(); ((TCPClient)client).Connect(_settings.ClientAddress.Ip, _settings.ClientAddress.Port); } else { client = new UDPClient(); if (_settings.ClientNATAddress == null || _settings.ClientNATAddress.Ip == null || _settings.ClientNATAddress.Ip.Trim().Length == 0) { ((UDPClient)client).Connect(_settings.ClientAddress.Ip, _settings.ClientAddress.Port); } else { ((UDPClient)client).Connect(_settings.ClientAddress.Ip, _settings.ClientAddress.Port, _settings.ClientNATAddress.Ip, _settings.ClientNATAddress.Port); } } if (!client.IsBound) { RaiseNetworkSceneFailedToBind(this, gameObject.scene); return; } UnregisterEventsClient(); _networker = client; RegisterEventsClient(); SceneReady(gameObject.scene); SceneManager.MoveGameObjectToScene(gameObject, gameObject.scene); RaiseNetworkSceneStart(this, gameObject.scene); }
private void Connect() { portNumber = "15937"; if (connectUsingMatchmaking) { ConnectToMatchmaking(); return; } ushort port; if (!ushort.TryParse(portNumber, out port)) { Debug.LogError("The supplied port number is not within the allowed range 0-" + ushort.MaxValue); return; } NetWorker client; if (useTCP) { client = new TCPClient(); ((TCPClient)client).Connect(ipAddress, (ushort)port); } else { client = new UDPClient(); if (natServerHost.Trim().Length == 0) { ((UDPClient)client).Connect(ipAddress, (ushort)port); } else { ((UDPClient)client).Connect(ipAddress, (ushort)port, natServerHost, natServerPort); } } Connected(client); }
public void Connect(string ip) { NetWorker client; if (useTCP) { client = new TCPClient(); ((TCPClient)client).Connect(ip, ServerInfo.SERVER_PORT); } else { client = new UDPClient(); if (natServerHost.Trim().Length == 0) { ((UDPClient)client).Connect(ip, ServerInfo.SERVER_PORT); } else { ((UDPClient)client).Connect(ip, ServerInfo.SERVER_PORT, natServerHost, natServerPort); } } Connected(client); }
private void button_login_Click(object sender, EventArgs e) { UDPClient udpClient = KevRegister.Get <UDPClient>(ClientItemsPrimaryKey.Socket_UDPClient, () => { udpClient = new UDPClient(); udpClient.ServerIPPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788); udpClient.Start(); return(udpClient); }); KevSocketModel ksModel = new KevSocketModel() { DeviceId = KevRegister.Get(UDPPrimaryKey.Client_ThisDeviceId, -1), MessageId = IdGenerator.NextId(), MessageType = MessageType.Login, NetworkType = NetworkType.Request }; if (!udpClient.SendMessage(ksModel)) { MessageBox.Show("连接服务器失败,请稍后尝试"); } }
public void Connect() { if (m_ConnectUsingMatchmaking) { ConnectToMatchmaking(); return; } ushort port; if (!ushort.TryParse(m_PortNumber.text, out port)) { Debug.LogError("The supplied port number is not within the allowed range 0-" + ushort.MaxValue); return; } NetWorker client; if (m_UseTCP) { client = new TCPClient(); ((TCPClient)client).Connect(m_IPAddress.text, (ushort)port); } else { client = new UDPClient(); if (m_NATServerHost.Trim().Length == 0) { ((UDPClient)client).Connect(m_IPAddress.text, (ushort)port); } else { ((UDPClient)client).Connect(m_IPAddress.text, (ushort)port, m_NATServerHost, NATServerPort); } } Connected(client); }
public void Connect() { if (connectUsingMatchmaking) { ConnectToMatchmaking(); return; } int port = ushort.Parse(portNumber.text); if (port < 0 || port > ushort.MaxValue) { Debug.LogError("The supplied port number is not within the allowed range 0-" + ushort.MaxValue); return; } NetWorker client; if (useTCP) { client = new TCPClient(); ((TCPClient)client).Connect(ipAddress.text, (ushort)port); } else { client = new UDPClient(); if (natServerHost.Trim().Length == 0) { ((UDPClient)client).Connect(ipAddress.text, (ushort)port); } else { ((UDPClient)client).Connect(ipAddress.text, (ushort)port, natServerHost, natServerPort); } } Connected(client); }
public void Connect2ClientsTest() { var client1 = new UDPClient(); var client2 = new UDPClient(); Console.WriteLine("Using port number: " + currentPort); client1.Connect("127.0.0.1", currentPort); Assert.IsTrue(client1.IsBound); WaitFor(() => { return(client1.IsConnected); }); client2.Connect("127.0.0.1", currentPort); Assert.IsTrue(client2.IsBound); WaitFor(() => { return(client2.IsConnected); }); client1.Disconnect(false); client2.Disconnect(false); WaitFor(() => { return(!client1.IsConnected); }); Assert.IsFalse(client1.IsBound); WaitFor(() => { return(!client2.IsConnected); }); Assert.IsFalse(client2.IsBound); }
public void Terminate() { if (!m_terminate) { m_terminate = true; if (null != m_loginClient) { m_loginClient.Close(); m_loginClient = null; } if (null != m_gateClient) { m_gateClient.Close(); m_gateClient = null; } if (null != m_crossClient) { m_crossClient.Close(); m_crossClient = null; } m_thread.Join(); m_thread = null; } }
static void Main(string[] args) { var s = new Base.MessageData(); s.desc = "12313"; Console.WriteLine(s.ToString()); var udpType = 0; var get = Console.ReadKey(); Console.WriteLine(); if (get.Key == ConsoleKey.Q) { UDPClient.Init(); UDPClient.GetRoomList(); udpType = 0; } else if (get.Key == ConsoleKey.W) { UDPServer.Init(); udpType = 1; } while (true) { string str = Console.ReadLine(); if (udpType == 0) { UDPClient.SendMsg(str); } else { UDPServer.SendMsg(str); } } }
public void StartAsClient(ECSNetworkManagerSetting pSettings) { _settings = pSettings; Disconnect(); InitializeDefaults(); NetWorker client; if (_settings.UseTCP) { client = new TCPClient(); ((TCPClient)client).Connect(_settings.ClientAddress.Host, _settings.ClientAddress.Port); } else { client = new UDPClient(); if (_settings.ClientNATAddress == null || _settings.ClientNATAddress.Host == null || _settings.ClientNATAddress.Host.Trim().Length == 0) { ((UDPClient)client).Connect(_settings.ClientAddress.Host, _settings.ClientAddress.Port); } else { ((UDPClient)client).Connect(_settings.ClientAddress.Host, _settings.ClientAddress.Port, _settings.ClientNATAddress.Host, _settings.ClientNATAddress.Port); } } if (!client.IsBound) { RaiseFailedToBind(this); return; } UnregisterEventsClient(); _networker = client; RegisterEventsClient(); RaiseStart(this); }
private bool UDPClient_dataSend_EventDataSend(byte[] data) { return(UDPClient.SendData(data)); }
public void Connect() { client = new UDPClient(); client.Connect(ip, port); Connected(client); }
/// <summary> /// Start the VOIP sending client /// </summary> /// <param name="hostAddress">The address for the VOIP to connect to</param> /// <param name="port">Port of the VOIP</param> public void StartClient(string hostAddress = "127.0.0.1", ushort port = 15959) { Socket = new UDPClient(); Setup(hostAddress, port); }
void generateMapAndPlayer(Hashtable mapInfo, PlayerSpawnDir spawnDir) { // get map information from the hash table string mapString = (string)mapInfo["map"]; rows = (int)mapInfo["row"]; columns = (int)mapInfo["column"]; currentStageHash = (string)mapInfo["hash"]; int HPStatus, APStatus; if (player != null) { HPStatus = player.m_HP; APStatus = player.m_AP; } else { HPStatus = (int)mapInfo["hp"]; APStatus = (int)mapInfo["ap"]; } string[] arrayMap = mapString.Split(','); // get item information from the hash table int[] itemCounts = new int[(int)(itemID.END + 1)]; int[] itemValues = new int[(int)(itemID.END + 1)]; for (int i = 0; i <= (int)(itemID.END); i++) { if (mapInfo.ContainsKey(i.ToString())) { Hashtable itemTable = (Hashtable)mapInfo[i.ToString()]; itemCounts[i] = (int)itemTable["items"]; itemValues[i] = (int)itemTable["value"]; } else { itemCounts[i] = 0; } } // find the gates int northGate = -111, southGate = -111, eastGate = -111, westGate = -111; for (int i = 0; i < columns; i++) { if (arrayMap[i] == "N") { northGate = i; break; } } for (int i = 0; i < columns; i++) { if (arrayMap[columns * (rows - 1) + i] == "S") { southGate = i; break; } } for (int i = 0; i < rows; i++) { if (arrayMap[columns - 1 + columns * (rows - 1 - i)] == "E") { eastGate = i; break; } } for (int i = 0; i < rows; i++) { if (arrayMap[columns * (rows - 1 - i)] == "W") { westGate = i; break; } } // floor generation for (int x = -2; x < columns + 2; x++) { for (int y = -3; y < rows + 3; y++) { int tileIndex = 0; if (x <= 0 || y <= 0 || x >= columns - 1 || y >= rows - 1) { tileIndex = 9; } else if (x == 1) { if (y == 1) { tileIndex = 6; } else if (y == rows - 2) { tileIndex = 0; } else { tileIndex = 3; } } else if (x == columns - 2) { if (y == 1) { tileIndex = 8; } else if (y == rows - 2) { tileIndex = 2; } else { tileIndex = 5; } } else { if (y == 1) { tileIndex = 7; } else if (y == rows - 2) { tileIndex = 1; } else { tileIndex = 4; } } instantiateAndAdd(floorTiles[tileIndex], x, y, holders[(int)(holderID.FLOOR)]); } } // cliff generation List <Vector3> rockTilePositions = new List <Vector3>(); List <Vector3> rockPositions = new List <Vector3>(); // cliff, SW side of the map instantiateAndAdd(cliffTiles[3], -1, -1, holders[(int)(holderID.CLIFF)]); for (int y = -3; y <= -2; y++) { for (int x = -2; x <= 0; x++) { rockTilePositions.Add(new Vector3(x, y, 0)); } } for (int y = -1; y <= 0; y++) { rockTilePositions.Add(new Vector3(-2, y, 0)); } // cliff, SE side of the map instantiateAndAdd(cliffTiles[15], columns, -1, holders[(int)(holderID.CLIFF)]); for (int y = -3; y <= -2; y++) { for (int x = columns - 1; x <= columns + 1; x++) { rockTilePositions.Add(new Vector3(x, y, 0)); } } for (int y = -1; y <= 0; y++) { rockTilePositions.Add(new Vector3((columns + 1), y, 0)); } // cliff, NW side of the map instantiateAndAdd(cliffTiles[7], -1, rows + 1, holders[(int)(holderID.CLIFF)]); for (int x = -2; x <= 0; x++) { rockTilePositions.Add(new Vector3(x, rows + 2, 0)); } for (int y = rows - 1; y <= rows + 1; y++) { rockTilePositions.Add(new Vector3(-2, y, 0)); } // cliff, NE side of the map instantiateAndAdd(cliffTiles[11], columns, rows + 1, holders[(int)(holderID.CLIFF)]); for (int x = columns - 1; x <= columns + 1; x++) { rockTilePositions.Add(new Vector3(x, rows + 2, 0)); } for (int y = rows - 1; y <= rows + 1; y++) { rockTilePositions.Add(new Vector3((columns + 1), y, 0)); } // cliff, south side for (int x = 1; x < columns - 1; x++) { if (x == southGate - 2) { instantiateAndAdd(cliffTiles[2], x, -1, holders[(int)(holderID.CLIFF)]); for (int y = -3; y <= -2; y++) { instantiateAndAdd(cliffTiles[4 + Random.Range(0, 2)], x, y, holders[(int)(holderID.CLIFF)]); } } else if (x == southGate + 2) { instantiateAndAdd(cliffTiles[14], x, -1, holders[(int)(holderID.CLIFF)]); for (int y = -3; y <= -2; y++) { instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], x, y, holders[(int)(holderID.CLIFF)]); } } else if (Mathf.Abs(x - southGate) >= 3) { instantiateAndAdd(cliffTiles[Random.Range(0, 2)], x, -1, holders[(int)(holderID.CLIFF)]); for (int y = -3; y <= -2; y++) { rockTilePositions.Add(new Vector3(x, y, 0)); } } } // cliff, north side for (int x = 1; x < columns - 1; x++) { if (x == northGate - 2) { instantiateAndAdd(cliffTiles[6], x, rows + 1, holders[(int)(holderID.CLIFF)]); instantiateAndAdd(cliffTiles[4 + Random.Range(0, 2)], x, rows + 2, holders[(int)(holderID.CLIFF)]); } else if (x == northGate + 2) { instantiateAndAdd(cliffTiles[10], x, rows + 1, holders[(int)(holderID.CLIFF)]); instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], x, rows + 2, holders[(int)(holderID.CLIFF)]); } else if (Mathf.Abs(x - northGate) >= 3) { instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], x, rows + 1, holders[(int)(holderID.CLIFF)]); rockTilePositions.Add(new Vector3(x, rows + 2, 0)); } } // cliff, west side for (int y = 1; y <= rows - 1; y++) { if (y == westGate + 3) { instantiateAndAdd(cliffTiles[6], -1, y, holders[(int)(holderID.CLIFF)]); instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], -2, y, holders[(int)(holderID.CLIFF)]); } else if (y == westGate - 1) { instantiateAndAdd(cliffTiles[2], -1, y, holders[(int)(holderID.CLIFF)]); instantiateAndAdd(cliffTiles[Random.Range(0, 2)], -2, y, holders[(int)(holderID.CLIFF)]); } else if (Mathf.Abs(y - (westGate + 1)) >= 3) { instantiateAndAdd(cliffTiles[4 + Random.Range(0, 2)], -1, y, holders[(int)(holderID.CLIFF)]); rockTilePositions.Add(new Vector3(-2, y, 0)); } } // cliff, east side for (int y = 1; y <= rows - 1; y++) { if (y == eastGate + 3) { instantiateAndAdd(cliffTiles[10], columns, y, holders[(int)(holderID.CLIFF)]); instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], columns + 1, y, holders[(int)(holderID.CLIFF)]); } else if (y == eastGate - 1) { instantiateAndAdd(cliffTiles[14], columns, y, holders[(int)(holderID.CLIFF)]); instantiateAndAdd(cliffTiles[Random.Range(0, 2)], columns + 1, y, holders[(int)(holderID.CLIFF)]); } else if (Mathf.Abs(y - (eastGate + 1)) >= 3) { instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], columns, y, holders[(int)(holderID.CLIFF)]); rockTilePositions.Add(new Vector3(columns + 1, y, 0)); } } // random generation of rock tiles foreach (Vector3 pos in rockTilePositions) { instantiateAndAdd( rockFloorTiles[Random.Range(0, rockFloorTiles.Length)], Mathf.FloorToInt(pos.x), Mathf.FloorToInt(pos.y), holders[(int)(holderID.CLIFF)] ); } // box colliders for the borders for (int x = 0; x < columns; x++) { for (int y = 0; y < rows; y++) { if (arrayMap[x + (rows - 1 - y) * columns] == "#") { Transform border = new GameObject("collider").transform; border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]); border.Translate(x, y, 0); border.gameObject.layer = LayerMask.NameToLayer("Object"); border.gameObject.AddComponent <BoxCollider2D>(); } } } if (northGate >= 1 && northGate < columns - 1) { for (int x = northGate - 1; x <= northGate + 1; x += 2) { Transform border = new GameObject("collider").transform; border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]); border.Translate(x, rows + 1f, 0); border.localScale += new Vector3(0, 2.0f, 0); border.gameObject.layer = LayerMask.NameToLayer("Object"); border.gameObject.AddComponent <BoxCollider2D>(); } } if (southGate >= 1 && southGate < columns - 1) { for (int x = southGate - 1; x <= southGate + 1; x += 2) { Transform border = new GameObject("collider").transform; border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]); border.Translate(x, -2f, 0); border.localScale += new Vector3(0, 2.0f, 0); border.gameObject.layer = LayerMask.NameToLayer("Object"); border.gameObject.AddComponent <BoxCollider2D>(); } } if (eastGate >= 1 && eastGate < rows - 1) { for (int y = eastGate - 1; y <= eastGate + 1; y += 2) { Transform border = new GameObject("collider").transform; border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]); border.Translate(columns + 0.5f, y, 0); border.localScale += new Vector3(1.0f, 0, 0); border.gameObject.layer = LayerMask.NameToLayer("Object"); border.gameObject.AddComponent <BoxCollider2D>(); } } if (westGate >= 1 && westGate < rows - 1) { for (int y = westGate - 1; y <= westGate + 1; y += 2) { Transform border = new GameObject("collider").transform; border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]); border.Translate(-1.5f, y, 0); border.localScale += new Vector3(1.0f, 0, 0); border.gameObject.layer = LayerMask.NameToLayer("Object"); border.gameObject.AddComponent <BoxCollider2D>(); } } // block generation for (int y = rows - 1; y >= 0; y--) { for (int x = 0; x < columns; x++) { if (arrayMap[x + (rows - 1 - y) * columns] == "b") { instantiateAndAdd(blockTiles, x, y, 0, holders[(int)(holderID.BLOCK)]); } } } // item generation for (int y = rows - 1; y >= 0; y--) { for (int x = 0; x < columns; x++) { for (int itemIdx = (int)(itemID.START); itemIdx <= (int)(itemID.END); itemIdx++) { if (arrayMap[x + (rows - 1 - y) * columns] == itemIdx.ToString() && itemCounts[itemIdx] > 0) { switch ((itemID)itemIdx) { case itemID.POTION1: Potion potion1 = ObjectFactory.createPotion(x, y, itemValues[itemIdx], (int)(itemID.POTION1)); potion1.transform.SetParent(holders[(int)(holderID.POTION)]); break; case itemID.POTION2: Potion potion2 = ObjectFactory.createPotion(x, y, itemValues[itemIdx], (int)(itemID.POTION2)); potion2.transform.SetParent(holders[(int)(holderID.POTION)]); break; case itemID.WEAPON: Weapon weapon = ObjectFactory.createWeapon(x, y, itemValues[itemIdx], (int)(itemID.WEAPON)); weapon.transform.SetParent(holders[(int)(holderID.WEAPON)]); break; } } } } } // player generation int playerX = 0; int playerY = 0; switch (spawnDir) { case PlayerSpawnDir.SPAWN_EAST: playerX = columns - 2; playerY = eastGate; break; case PlayerSpawnDir.SPAWN_NORTH: playerX = northGate; playerY = rows - 2; break; case PlayerSpawnDir.SPAWN_WEST: playerX = 1; playerY = westGate; break; case PlayerSpawnDir.SPAWN_SOUTH: playerX = southGate; playerY = 1; break; case PlayerSpawnDir.SPAWN_NONE: bool playerPlaced = false; bool hasEmptySpace = false; for (int y = rows - 1; y >= 0; y--) { for (int x = 0; x < columns; x++) { if (arrayMap[x + (rows - 1 - y) * columns] == "u") { if (!playerPlaced) { playerPlaced = true; playerX = x; playerY = y; } } else if (arrayMap[x + (rows - 1 - y) * columns] == "f") { hasEmptySpace = true; } } } while (!playerPlaced && hasEmptySpace) { playerX = Random.Range(1, columns - 1); playerY = Random.Range(1, columns - 1); if (arrayMap[playerX + (rows - 1 - playerY) * columns] == "f") { playerPlaced = true; } } break; } if (player == null) { player = ObjectFactory.createPlayer(playerX, playerY, HPStatus, APStatus); player.transform.SetParent(holders[(int)(holderID.PLAYER)]); } else { player.Initialize(playerX, playerY, HPStatus, APStatus); } // get peer's ip addresses who are in this area! peerIPList.Clear(); ArrayList listIPs = (ArrayList)mapInfo["ips"]; foreach (string ip in listIPs) { if (ip != getMyIP()) { peerIPList.Add(ip); } } // peer player initialization peerUDPClients.Clear(); foreach (string ip in peerIPList) { GameObject peer = new GameObject("peer UDP client"); UDPClient peerClient = peer.AddComponent <UDPClient>(); peerClient.InitiateSocket(ip, 12346); peerUDPClients.Add(peer); Hashtable data = new Hashtable(); data.Add("action", "myinfo"); data.Add("hash", currentStageHash); data.Add("username", SystemInfo.deviceUniqueIdentifier); data.Add("ip", getMyIP()); data.Add("xpos", playerX); data.Add("ypos", playerY); peerClient.sendJSONObject(data); } }
void Start() { client = new UDPClient(port, OnReceive, OnError); }
public AuthServer() { _packetLogger = new PacketLogger(); _logger = new Logger() { WriteToConsole = true }; _logger.Load(Path.Combine("logs", string.Format("auth_{0}.log", DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss")))); AppDomain.CurrentDomain.UnhandledException += (s, e) => { Error(s, new ExceptionEventArgs((Exception)e.ExceptionObject)); Environment.Exit(0); }; _packetLogger.Load("auth_packets.log"); _logger.Info("Loaded Packet Logger"); Stopwatch sw = Stopwatch.StartNew(); AuthConfig.Load(); sw.Stop(); _logger.Info("Loaded Auth Configuration in {0} ms", sw.Elapsed.TotalMilliseconds); _logger.Info("Starting up server connections..."); _server = new TcpServer(IPAddress.Parse(AuthConfig.Instance.IP), AuthConfig.Instance.Port); _server.PacketReceived += HandlePacket; _server.Error += Error; // // Initalize a list of ports // ushort[] ports = { 38915, 38917 }; for (uint i = 0; ports.Length > i; i++) { // Handle NAT tests before starting... switch (i) { case 0: _natServer = new UDPClient(ports[0]); _natServer.PacketReceived += HandleNATTest; _natServer.Error += Error; _logger.InfoAuth("NAT Test successful at Port {0}", ports[0]); break; case 1: _natServer2 = new UDPClient(ports[1]); _natServer2.PacketReceived += HandleNATTest2; _natServer2.Error += Error; _logger.InfoAuth("NAT Test successful at Port {0}", ports[1]); break; default: break; } } // Bind to pipe/tcp/http settings in configuration var isMono = Type.GetType("Mono.Runtime") != null; switch (AuthConfig.Instance.Remote.Binding) { case "pipe": if (isMono) { _logger.Error("pipe is not supported in mono, use http!"); Environment.Exit(1); return; } _remoteServer = new RemoteServer(this, ERemoteBinding.Pipe, string.Format("localhost/AuthServer/{0}/", SHA256.ComputeHash(AuthConfig.Instance.Remote.Password))); break; case "tcp": if (isMono) { _logger.Error("tcp is not supported in mono, use http!"); Environment.Exit(1); return; } _remoteServer = new RemoteServer(this, ERemoteBinding.Pipe, string.Format("{0}:{1}/AuthServer/{2}/", AuthConfig.Instance.Remote.Server, AuthConfig.Instance.Remote.Port, SHA256.ComputeHash(AuthConfig.Instance.Remote.Password))); break; case "http": _remoteServer = new RemoteServer(this, ERemoteBinding.Http, string.Format("{0}:{1}/AuthServer/{2}/", AuthConfig.Instance.Remote.Server, AuthConfig.Instance.Remote.Port, SHA256.ComputeHash(AuthConfig.Instance.Remote.Password))); break; default: _logger.Error("Invalid remote binding '{0}'", AuthConfig.Instance.Remote.Binding); Environment.Exit(1); return; } _remoteServer.AddServiceEndpoint(typeof(IAuthRemote), "IAuthRemote"); }
public AuthServer() { _packetLogger = new PacketLogger(); _logger = new Logger() { WriteToConsole = true }; _logger.Load(Path.Combine("logs", string.Format("auth_{0}.log", DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss")))); AppDomain.CurrentDomain.UnhandledException += (s, e) => { Error(s, new ExceptionEventArgs((Exception)e.ExceptionObject)); Environment.Exit(0); }; _packetLogger.Load("auth_packets.log"); _logger.Info("Loaded Packet Logger"); Stopwatch sw = Stopwatch.StartNew(); AuthConfig.Load(); sw.Stop(); _logger.Info("Loaded Auth Configuration in {0} ms", sw.Elapsed.TotalMilliseconds); _logger.Info("Starting up server connections..."); _server = new TcpServer(IPAddress.Parse(AuthConfig.Instance.IP), AuthConfig.Instance.Port); _server.PacketReceived += HandlePacket; _server.Error += Error; // // Initalize a list of ports // ushort[] ports = { 38915, 38917 }; for (uint i = 0; ports.Length > i; i++ ) { // Handle NAT tests before starting... switch (i) { case 0: _natServer = new UDPClient(ports[0]); _natServer.PacketReceived += HandleNATTest; _natServer.Error += Error; _logger.InfoAuth("NAT Test successful at Port {0}", ports[0]); break; case 1: _natServer2 = new UDPClient(ports[1]); _natServer2.PacketReceived += HandleNATTest2; _natServer2.Error += Error; _logger.InfoAuth("NAT Test successful at Port {0}", ports[1]); break; default: break; } } // Bind to pipe/tcp/http settings in configuration var isMono = Type.GetType("Mono.Runtime") != null; switch (AuthConfig.Instance.Remote.Binding) { case "pipe": if (isMono) { _logger.Error("pipe is not supported in mono, use http!"); Environment.Exit(1); return; } _remoteServer = new RemoteServer(this, ERemoteBinding.Pipe, string.Format("localhost/AuthServer/{0}/", SHA256.ComputeHash(AuthConfig.Instance.Remote.Password))); break; case "tcp": if (isMono) { _logger.Error("tcp is not supported in mono, use http!"); Environment.Exit(1); return; } _remoteServer = new RemoteServer(this, ERemoteBinding.Pipe, string.Format("{0}:{1}/AuthServer/{2}/", AuthConfig.Instance.Remote.Server, AuthConfig.Instance.Remote.Port, SHA256.ComputeHash(AuthConfig.Instance.Remote.Password))); break; case "http": _remoteServer = new RemoteServer(this, ERemoteBinding.Http, string.Format("{0}:{1}/AuthServer/{2}/", AuthConfig.Instance.Remote.Server, AuthConfig.Instance.Remote.Port, SHA256.ComputeHash(AuthConfig.Instance.Remote.Password))); break; default: _logger.Error("Invalid remote binding '{0}'", AuthConfig.Instance.Remote.Binding); Environment.Exit(1); return; } _remoteServer.AddServiceEndpoint(typeof(IAuthRemote), "IAuthRemote"); }
public void SendToClient(UDPClient client, byte[] data) { Debug.Log("Sent: " + Encoding.UTF8.GetString(data)); serverClient.Send(data, data.GetLength(0), client.endPoint); }
//don't use on main thread public void ReadInput() { SendToClient(Connectedclient, UDPClient.StringToBytes(Console.ReadLine())); serverClient.BeginReceive(new AsyncCallback(receive), null); }
public UdpClientHelper() { udpClient = new UDPClient(); }
private static void Main() { UDPClient sendObj = new UDPClient(); sendObj.init(); }
public override void init(MsgConsumer consumer) { for (int i = 0; i < serverCount;i++ ) { udpServers[i] = new UDPServer(local[i], this); } for (int i=0; i< clientCount;i++) { udpClients[i] = new UDPClient(remote[i]); } if (clientCount > 1) { deliveryThreads = new SplitThread[clientCount]; for (int i=0; i < clientCount; i++) { deliveryThreads[i] = new SplitThread(i, udpClients[i], msgID); } } base.init(consumer); }
public static void RegisterEvent(OutgoingGameEvent gameEvent) { byte[] message = gameEvent.GetSerialized(); UDPClient.GetInstance().SendMessage(message, message.Length); }
void initUDP() { udpClient = new UDPClient(true); udpClient.Initiate(ConnectionData.selectedIP, ConnectionData.portOutUDP); }
private void Start() { localIP = UDPClient.GetLocalIPAddress(); }
// initialization method public void Initialize(int posX, int posY, int HPStatus, int APStatus) { m_posX = posX; m_posY = posY; m_HP = HPStatus; m_AP = APStatus; boxCollider = GetComponent<BoxCollider2D>(); if (boardManager == null) { boardManager = GameObject.Find("BoardManager").GetComponent<BoardManager>(); } if (client == null) { client = boardManager.GetComponent<UDPClient>(); } transform.position = new Vector3(posX, posY, 0); }
//private ObservableCollection<RssItem> listViewCollection; public MainWindow() { using (MemoryStream memory = new MemoryStream()) { Properties.Resources.icon.Save(memory); memory.Position = 0; BitmapImage bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = memory; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); Icon = bitmapImage; } string fullPath = AppDomain.CurrentDomain.BaseDirectory; InitializeComponent(); CBServis = new CB.DailyInfoSoapClient(); try { System.Data.DataSet Curs = CBServis.GetCursOnDate(System.DateTime.Now); TextUS.Content = Curs.Tables[0].Rows[9].ItemArray[2].ToString(); TextEVR.Content = Curs.Tables[0].Rows[10].ItemArray[2].ToString(); } catch (Exception) { TextUS.Content = "Не доступно"; TextEVR.Content = TextUS.Content; } ipDispatcher = ""; rssChanels = this.LoadChannelsFromFile("RssChannels.bin"); Logger.Write("загружены из файла rss каналы"); this.UpdateChannels(); //listViewCollection = new ObservableCollection<RssItem>(rssChanels[0].Articles); lvArticles.ItemsSource = rssChanels[0].Articles; // аля неудачная попытка сделать красивый интерфейс // create buttons for articles categories //for (int i = 0; i < rssChanels.Count; i++) //{ // var btnCateg = new Button() { Name = "btnCat" + i, Content = rssChanels[i].Category }; // btnCateg.Click += RssCateg_Click; // btnCateg.Uid = i.ToString(); // btnCateg.Style = this.FindResource("channelBtn") as Style; // CategoryWrap.Children.Add(btnCateg); //} foreach (RssChannel channel in rssChanels) { cmbCategoryList.Items.Add(channel.Category); } cmbCategoryList.SelectedIndex = 0; broadCast = new UDPClient(); broadCast.onMessage += this.UDP_Receive; broadCast.Start(); Logger.Write("запущен поток на прослушку UDP"); }
public SplitThread(int index, UDPClient udpClient, int baseMsgID) { this.msgID = baseMsgID; this.index = index; this.udpClient = udpClient; innerThread = new Thread(new ThreadStart(distribute)); innerThread.Start(); Thread.Sleep(5); }
public void PostAwake() { UDPClient.cs = this; }
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); }
void Start() { Instance = this; try { GC = GameObject.FindGameObjectWithTag("GameController").GetComponent <GameController>(); } catch (Exception) { throw; } GC.CurrentGpsPosition = Config.DebugGpsPosition; // tryToLogin("Lukas", "1234567"); //TODO: MAKE SURE THAT THE GAME DOESN'T CRASH IF SERVER CONNECTION CAN'T BE ESTABLISHED! // Helper.ServerRequest login = new Helper.ServerRequest() {request = Helper.ServerRequestType.LogIn}; // StartCoroutine(SendRequest<Helper.LoginCredentials, Helper.Player>(login, new Helper.LoginCredentials(){name = "Lukas", password = "******"},true)); // Helper.ServerRequest newplayer = new Helper.ServerRequest() {request = Helper.ServerRequestType.NewPlayer}; // StartCoroutine(SendRequest<Helper.LoginCredentials, Helper.Player>(newplayer, new Helper.LoginCredentials(){name = "Lars", password = "******"},true)); // Helper.ServerRequest updateplayer = new Helper.ServerRequest() {request = Helper.ServerRequestType.UpdatePlayer}; // StartCoroutine(SendRequest<Helper.Player, string>(updateplayer, new Helper.Player("Lars","1234567",2) {xp = 100},true)); // Helper.ServerRequest sendPos = new Helper.ServerRequest() {request = Helper.ServerRequestType.SendPosition}; // Debug.Log(JsonUtility.ToJson(new Helper.PlayerLocation(){name = "Lars", id = 2, timestamp = DateTime.Now.ToString(), position = new Vector2(48.05f, 8.2f)})); // StartCoroutine(SendRequest<Helper.PlayerLocation, string>(sendPos, new Helper.PlayerLocation(){name = "Lars", id = 2, timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"), position = new Vector2(48.05f, 8.2f)},true)); // StartCoroutine(SendRequest<Helper.PlayerLocation, string>(sendPos, new Helper.PlayerLocation(){name = "Lukas", id = 0, timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"), position = new Vector2(48.0501f, 8.202f)},true)); // Helper.ServerRequest getPos = new Helper.ServerRequest() {request = Helper.ServerRequestType.RecievePositions}; // StartCoroutine(SendRequest<Vector2,List<Helper.PlayerLocation>>(getPos, new Vector2(48.05f, 8.2f), true)); /* * Helper.PointOfAction poa = new Helper.PointOfAction() {name = "Furtwangen", attack = Helper.Attacks.None, position = new Vector2(GC.CurrentGpsPosition.Latitude, GC.CurrentGpsPosition.Longitude), power = 0}; * * // print (Cube.position); * byte[] data = new byte[1024]; * IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); * * Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); * * // string welcome = "Hello, what's up?"; * Debug.Log(poa); * Helper.ServerRequest sr = new Helper.ServerRequest() {request = Helper.ServerRequestType.SendPosition}; * data = Encoding.ASCII.GetBytes(JsonUtility.ToJson(sr) +";"+JsonUtility.ToJson(poa)); * Debug.Log(data); * server.SendTo(data, data.Length, SocketFlags.None, ipep); * * IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); * EndPoint tmpRemote = (EndPoint)sender; * * data = new byte[1024]; * int recv = server.ReceiveFrom(data, ref tmpRemote); * * Debug.Log (String.Format("Message received from {0}:", tmpRemote.ToString())); * Debug.Log (Encoding.ASCII.GetString(data, 0, recv)); * Debug.Log (JsonUtility.FromJson<Helper.ServerRequest>(Encoding.ASCII.GetString(data, 0, recv))); * * // server.SendTo(Encoding.ASCII.GetBytes(Cube.position.ToString()), tmpRemote); * * * Console.WriteLine("Stopping client"); * server.Close(); */ }