private void OnUpdate() { if (m_ClientNetwork != null) { ClientNetworkStatus curStatus = m_ClientNetwork.Status; if (curStatus != m_ClientStatus) { m_ClientStatus = curStatus; if (m_ClientStatus == ClientNetworkStatus.Disconnected) { ShowNotification(new GUIContent("Disconnected")); m_ClientNetwork = null; } else if (m_ClientStatus == ClientNetworkStatus.Connecting) { ShowNotification(new GUIContent("Connecting...")); } else if (m_ClientStatus == ClientNetworkStatus.Connected) { ShowNotification(new GUIContent("Connected")); } else if (m_ClientStatus == ClientNetworkStatus.Disconnecting) { ShowNotification(new GUIContent("Disconnecting...")); } Repaint(); } } }
public void Initialise(IEnumerable <int> playerIDs) { foreach (var playerID in playerIDs) { if (ClientNetwork.getPID() == playerID) { var player = Instantiate(PlayerPrefab, new Vector3(), new Quaternion()); player.GetComponent <PlayerController>().StateManager = StateManager; PlayerState state = new PlayerState { Position = new Vector2(0, 0), Orientation = Direction.Up, PlayerID = playerID, HP = 100f }; player.GetComponent <PlayerController>().State = state; PlayerDict.Add(playerID, player); } else { var player = Instantiate(RemotePlayerPrefab, new Vector3(), new Quaternion()); player.GetComponent <Player>().StateManager = StateManager; PlayerState state = new PlayerState { Position = new Vector2(0, 0), Orientation = Direction.Up, PlayerID = playerID, HP = 100f }; player.GetComponent <Player>().State = state; PlayerDict.Add(playerID, player); } } }
// Use this for initialization void Start() { position = transform.position; rotation = transform.rotation; origScene = gameObject.scene.name; // If our network id hasn't been set, ask the server to give us one if (networkId == -1) { ClientNetwork client = FindObjectOfType <ClientNetwork>(); if (client == null) { Debug.LogError("NetworkId::Start() has been called without a ClientNetwork being available"); this.enabled = false; return; } client.ConnectNetworkSync(this); } else { // Check if we own this object if (clientNet.isOwned(networkId)) { isOwned = true; } } #if UNITY_EDITOR for (int i = 0; i < previousPostions.Length; i++) { previousPostions[i] = new PreviousPositionData(); previousPostions[i].color = new Color(0.0f, 0.0f, 0.0f, 0.0f); } #endif }
public override bool LeftClick() { if (buttons[0].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.currentGui = null; return(true); } else if (buttons[1].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.currentGui = new GuiSettings(this); return(true); } else if (buttons[2].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { ClientNetwork net = ClientNetwork.GetClientNetwork(); net.Stop(); return(true); } else if (buttons[3].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.currentGui = new GuiStatistics(); return(true); } else { return(false); } }
public override void _Ready() { if (!_useNetwork) { GetTree().ChangeScene("res://client/PaintRoot.tscn"); return; } _network = (ClientNetwork)GetNode("/root/PaintNetwork"); _userContainer = (Container)GetNode("CenterContainer/HBoxContainer/UserContainer"); var inputNode = GetNode("CenterContainer/HBoxContainer/InputContainer"); _name = (LineEdit)inputNode.GetNode("Name"); _host = (Button)inputNode.GetNode("Host"); _join = (Button)inputNode.GetNode("Join"); _start = (Button)inputNode.GetNode("Start"); _cancel = (Button)inputNode.GetNode("Cancel"); _host.Connect("pressed", this, nameof(RequestHost)); _join.Connect("pressed", this, nameof(RequestJoin)); _start.Connect("pressed", this, nameof(RequestStart)); _cancel.Connect("pressed", this, nameof(RequestCancel)); _network.Connect(nameof(GameState.LobbyChanged), this, nameof(UpdatePlayerList)); _network.Connect(nameof(GameState.GameEnded), this, nameof(GameEnded)); }
private void Start() { clientEx = FindObjectOfType <ExampleClient>(); clientNet = FindObjectOfType <ClientNetwork>(); gameManager = FindObjectOfType <GameManager>(); rb = GetComponent <Rigidbody>(); }
public static void InitNetwork() { if (EditorLidgrenNetwork == null) { var config = new NetworkConfiguration( ClientConfiguration.Instance.Host, ClientConfiguration.Instance.Port ); var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream("Intersect.Editor.public-intersect.bek")) { var rsaKey = EncryptionKey.FromStream <RsaKey>(stream); Debug.Assert(rsaKey != null, "rsaKey != null"); EditorLidgrenNetwork = new ClientNetwork(config, rsaKey.Parameters); } EditorLidgrenNetwork.Handler = PacketHandler.HandlePacket; EditorLidgrenNetwork.OnDisconnected += HandleDc; EditorLidgrenNetwork.OnConnectionDenied += delegate { Connecting = false; ConnectionDenied = true; }; } if (!Connected) { Connecting = true; if (!EditorLidgrenNetwork.Connect()) { Log.Error("An error occurred while attempting to connect."); } } }
public override void Connect(string host, int port) { if (ClientLidgrenNetwork != null) { ClientLidgrenNetwork.Close(); ClientLidgrenNetwork = null; } var config = new NetworkConfiguration(ClientConfiguration.Instance.Host, ClientConfiguration.Instance.Port); var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream("Intersect.Client.public-intersect.bek")) { var rsaKey = EncryptionKey.FromStream <RsaKey>(stream); Debug.Assert(rsaKey != null, "rsaKey != null"); ClientLidgrenNetwork = new ClientNetwork(config, rsaKey.Parameters); } if (ClientLidgrenNetwork == null) { return; } ClientLidgrenNetwork.Handler = AddPacketToQueue; ClientLidgrenNetwork.OnConnected += delegate { OnConnected(); }; ClientLidgrenNetwork.OnDisconnected += delegate { OnDisconnected(); }; ClientLidgrenNetwork.OnConnectionDenied += delegate { OnConnectionFailed(true); }; if (!ClientLidgrenNetwork.Connect()) { Log.Error("An error occurred while attempting to connect."); } }
public void SetPID() { if (PID == null) { PID = ClientNetwork.getPID(); } }
void cn_Received(ClientNetwork cn, byte[] buffer) { byte[] by_header = new byte[2]; Array.Copy(buffer, 0, by_header, 0, 2); short header = BitConverter.ToInt16(by_header, 0); string[] cmd = Encoding.UTF8.GetString(buffer, 2, buffer.Length - 2).Split('|'); switch (header) { case (int)NetworkHEADER.DOCONNECTION: ServerHost = cmd[0]; PacketSender ps = new PacketSender(ClientNetwork.ClientSocket); ps.Send(NetworkHEADER.CONNECTION, cn.getsendstring()); break; case (int)NetworkHEADER.DISCONNECT: cn.Close(); MessageBox.Show("You Are Kicked From Session"); break; case (int)NetworkHEADER.DENIED: cn.Close(); MessageBox.Show("Server Denied Your Connection \n Check Server Or Max Players"); break; case (int)NetworkHEADER.PLISTGET: po.SendToServerP(); break; case (int)NetworkHEADER.POLISTGET: po.SendToServerPO(); break; } }
private void Continue_Click(object sender, EventArgs e) { CheckGameRun(); if (!CheckProcess("Steam")) { MessageBox.Show("Can't find Steam Client"); Process.GetCurrentProcess().Kill(); return; } if (!ClientNetwork.Connected) { Continue.Enabled = false; try { CN = new ClientNetwork(ServerIP.Text, 26974); } catch (Exception EX) { MessageBox.Show(EX.Message); return; } CN.Connect(); CN.Disconnected += new ClientNetwork.DisconnectedEventHandler(cn_Disconnected); CN.Received += new ClientNetwork.ReceivedEventHandler(cn_Received); timer1.Start(); // 220.120.94.93:27015 } }
public void TestClientNetwork() { byte[] toSend = new byte[10]; string host = "asd"; int port = 1000; Mock <IDataSocket> mockDataSocket = new Mock <IDataSocket>(); mockDataSocket.Setup(x => x.getMessage()).Returns <byte[]>(null); Mock <IClientSocket> mockClientSocket = new Mock <IClientSocket>(); mockClientSocket.Setup(x => x.connect(It.IsAny <string>(), It.IsAny <Int32>())); mockClientSocket.Setup(x => x.handle()).Returns(mockDataSocket.Object); Mock <IBuilder <IClientSocket> > mockClientSocketBuilder = new Mock <IBuilder <IClientSocket> >(); mockClientSocketBuilder.Setup(x => x.Build()).Returns(mockClientSocket.Object); ClientNetwork clientNetwork = new ClientNetwork(mockClientSocketBuilder.Object); clientNetwork.Connect(host, port); for (int i = 0; i < 100; i++) { clientNetwork.Handle(); } clientNetwork.Send(toSend); mockClientSocket.Verify(x => x.connect(host, port)); mockDataSocket.Verify(m => m.send(toSend)); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); ClientNetwork client = new ClientNetwork("127.0.0.1", 9080); client.OnNetConnected = () => { Console.WriteLine("Client connected"); }; client.OnDataReceived = (dataBytes) => { Console.WriteLine("OnMessage:" + Encoding.UTF8.GetString(dataBytes)); }; client.ConnectAsync(); while (true) { if (client.IsConnected) { client.DoUpdate(0.1f); Random r = new Random(); var v = r.Next(0, 10); if (v > 5) { client.SendAsync(Encoding.UTF8.GetBytes("Client Send Data,v = " + v)); } } Thread.Sleep(100); } }
void Init() { config = new ConfigReader("ClientConfig.txt"); UnitMovement.SetFrameRate(config.GetInt("FrameRate")); PlayerScript.VisionRadius = config.GetFloat("VisionRadius"); client = new ClientNetwork(); Connect(); }
public static void Disconnect() { if (ClientNetwork != null) { ClientNetwork.Close(); } Debug.Log("Отключение от сервера"); }
public GateAdaptor(string connIp, int port) { handle = new ClientNetwork(connIp, port) { ConnectorConnected = OnHandleConnected, ConnectorDisconnected = OnHandleDisconnected, ConnectorMessageReceived = OnHandleMessageReceived, }; }
private void Disconnect() { if (m_ClientNetwork != null) { m_ClientNetwork.Disconnect(); m_ClientNetwork = null; } m_ClientStatus = ClientNetworkStatus.None; }
public override bool LeftClick() { if (buttons[0].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.SetWorld(new World(true)); core.currentGui = null; Thread t = new Thread(StartLocalServer); t.Start(); Core.console.AddDebugString("Starting client world..."); ClientNetwork.GetClientNetwork().Start(); return(true); } else if (buttons[1].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.currentGui = new GuiConnect(false); return(true); } else if (buttons[2].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.currentGui = new GuiConnect(true); return(true); } else if (buttons[3].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.currentGui = new GuiSettings(this); return(true); } else if (buttons[4].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.isExit = true; if (ServerCore.GetServerCore() != null && ServerCore.GetServerCore().GetServer().Status == NetPeerStatus.Running) { Core.console.AddDebugString("Closing server..."); Thread t = new Thread(() => ServerCore.GetServerCore().Stop()); t.Start(); //ServerCore.instance.Stop(); } return(true); } else if (Settings.isDebug && buttons[5].Rect.Contains(new Point((int)core.inputManager.cursor.Position.X, (int)core.inputManager.cursor.Position.Y))) { core.SetWorld(new World(true)); int[] components = { 1, 1, 1, 1, 1, 1, 1 }; Ship s = new Ship(Vector2.Zero, Vector2.Zero, Faction.Human, ShipType.HumanSmall1, components, world, 0, 0); s.shipName = "Debug"; GunSlot[] gs = { new GunSlot(GunType.PlasmSmall, s), null }; s.AddGuns(gs); world.ships.Add(s); core.currentGui = new GuiSelectFaction(); return(true); } else { return(false); } }
private void ConnectServer() { if (m_ClientNetwork != null) { m_ClientNetwork.Disconnect(); } m_ClientNetwork = new ClientNetwork("LogClientNetwork"); m_ClientNetwork.RegistAllMessageHandler(this); m_ClientNetwork.Connect(m_IPAddressString, LogNetUtill.PORT); }
public override void _Ready() { var network = new ClientNetwork { Name = "PaintNetwork" }; GetTree().Root.AddChild(network); GetTree().ChangeScene("res://client/Lobby.tscn"); }
protected override void OnDestroy() { if (clientNetwork != null && clientNetwork.IsConnected) { clientNetwork.Dispose(); clientNetwork = null; } base.OnDestroy(); }
//OnDisable()和OnApplicationQuit()看狀況自行選擇一個使用即可 //由於這是示範,所以讓兩個函數都做同樣的事情 private void OnDisable() { //Unity在離開當前場景後會自動呼叫這個函數 if (client != null) { client.Exit(); client = null; } MessageText.SetMessage("OnDisable()"); }
public void Update() { if (!nwgm) { nwgm = GameObject.Find("NetworkGameManager").GetComponent <NetworkGameManager>(); } if (!client && !nwgm.game_finished) { client = GameObject.Find("ClientNetworkManager").GetComponent <ClientNetwork>(); } }
private void OnApplicationQuit() { //當應用程式結束時會自動呼叫這個函數 if (client != null) { client.Exit(); client = null; } MessageText.SetMessage("OnApplicationQuit()"); }
public Pewness(InputManager inputManager, TimeSource timeSource, ClientNetwork clientNetwork, GameStuffFactory stuffFactory, LoggerFactory loggerFactory) { _timeSource = timeSource; _inputManager = inputManager; clientNetwork.OnServerWelcome += OnServerWelcome; clientNetwork.OnServerUpdateLazers += QueueUpdateLazers; clientNetwork.OnServerUpdateCircle += QueueUpdateCircle; clientNetwork.GetMyGameObjects = GetMyGameObjects; _overlay = new Overlay(GetCircles, timeSource); _stuffFactory = stuffFactory; _logger = loggerFactory.CreateLogger(GetType()); }
static void Main(string[] args) { //Create new client network instance on ip / port //associate event handlers, begin listening ClientNetwork network = new ClientNetwork("127.0.0.1", 9150); network.OnConnected += OnConnected; network.BeginConnect(); //Load core .DLL LoadLibrary(); Process.GetCurrentProcess().WaitForExit(); }
// Use this for initialization void Awake() { // Make sure we have a ClientNetwork to use if (clientNet == null) { clientNet = GetComponent <ClientNetwork>(); } if (clientNet == null) { clientNet = (ClientNetwork)gameObject.AddComponent(typeof(ClientNetwork)); } }
public static void DestroyNetwork() { try { EditorLidgrenNetwork.Close(); EditorLidgrenNetwork = null; } catch (Exception) { // ignored } }
public static ClientNetwork GetInstance() { if (clientNetwork == null) { clientNetwork = new ClientNetwork(new MessageEncoder(), new MessageDecoder()); EditorApplication.update += () => { clientNetwork.DoUpdate(Time.deltaTime, Time.unscaledDeltaTime); }; } return(clientNetwork); }
public static bool SendToServer(string KeyNetwork, object DataObject = null, int WindowUid = -1) { try { Debug.Log("Подготовка запроса для отправки на сервер. Информация о запросе: \n" + $"KeyNetwork - {KeyNetwork}, WindowUid - {WindowUid}"); if (!ClientNetwork.Connected) { Debug.LogWarning("Не удалось проверить соединение с сервером, запрос отклонён!"); return(false); } byte[] DataBytes; if (DataObject != null && DataObject.GetType().Name == "Byte[]") { DataBytes = (byte[])DataObject; } else { DataBytes = Package.Packaging((DataObject == null) ? "" : DataObject); } var Receiver = new MResponse(); Receiver.WindowUid = WindowUid; Receiver.KeyNetwork = KeyNetwork; Receiver.DataBytes = DataBytes; byte[] WriteDataBytes = Package.Packaging(Receiver); try { ClientNetwork.Send(WriteDataBytes); } catch (SocketException ex) { Debug.LogError("Возникла ошибка при попытке отправить запрос на сервер. " + "Код ошибки:\n" + ex); } return(true); } catch (Exception ex) { Debug.LogError("Возникла ошибка при создании экземпляра транспортировки. " + "Код ошибки:\n" + ex); } return(false); }
static UltimaClient() { Status = UltimaClientStatus.Unconnected; _ClientNetwork = new ClientNetwork(); registerPackets(); }