public void NetworkManagerConnectionSendTest() { // arrange string sendMessage = "My Message"; NetworkManager host = new NetworkManager(5000); host.DataFormat = DataFormat.TextMessages; string receivedResult = string.Empty; host.NetworkMessageEvent += delegate(object sender, NetworkMessageEventArgs args) { receivedResult = args.Message; }; // act bool resultStart = host.Start(); NetworkManagerState resultState = host.State; NetworkManagerClient client = new NetworkManagerClient(); string connectResult = client.Connect(5000); client.Send(Encoding.UTF8.GetBytes(sendMessage)); // assert Assert.IsTrue(resultStart, "Start result must be 'True'"); Assert.IsTrue(resultState == NetworkManagerState.Running, "The state must be 'Running'"); Assert.IsTrue(connectResult == "Success", "The connect methode must return 'Success'"); Assert.IsTrue(receivedResult == sendMessage, "Received message must the same of sended message."); }
public NetworkManager() { mFrameSentPackets = new List <string>(); mComputerName = Dns.GetHostName(); #if FRB_MDX localIP = Dns.GetHostByName(mComputerName); #else localIP = Dns.GetHostEntry(mComputerName); #endif mReceivedText = new List <string>(); mReceivedBytes = new List <Byte[]>(); mReceivedPackets = new List <BasePacket>(); local = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); localControlledSprites = new List <NetSprite>(); remoteControlledSprites = new List <NetSprite>(); pendingAddRemoteSprites = new List <NetSprite>(); mState = NetworkManagerState.Disconnected; mComputerID = 0; connectedTo = new List <int>(); mNamesConnectedTo = new List <string>(); mDelayedByteArrays = new List <DelayedByteArray>(); dataToSend = new MemoryStream(); }
public void Connect(string ipAddress) { try { mState = NetworkManagerState.AttemptingConnection; IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), 9050); remote = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); remote.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, 1); remote.Connect(iep); mNamesConnectedTo.Add(""); connectedTo.Add(0); mState = NetworkManagerState.ConnectedAsClient; MemoryStream ms = new MemoryStream(); ms.Write(BitConverter.GetBytes(1 + this.mComputerName.Length), 0, 4); ms.WriteByte((byte)('N')); ms.Write(Encoding.ASCII.GetBytes(mComputerName), 0, mComputerName.Length); remote.Send(ms.ToArray(), (int)ms.Length, 0); } catch (Exception) { mState = NetworkManagerState.ConnectAsClientFailed; } }
public void NetworkManagerProtocolErrorTest() { // arrange // SensorValueRawDataModel string sendMessage = NetworkProtocol.CreateMessage("Das ist kein Json objekt"); NetworkManager host = new NetworkManager(5000); host.DataFormat = DataFormat.JsonObject; string receivedResult = string.Empty; host.NetworkMessageEvent += delegate(object sender, NetworkMessageEventArgs args) { receivedResult = args.Message; }; NetworkManagerClient client = new NetworkManagerClient(); // act bool resultStart = host.Start(); NetworkManagerState resultState = host.State; string connectResult = client.Connect(5000); client.Send(Encoding.UTF8.GetBytes(sendMessage)); // assert Assert.IsTrue(resultStart, "Start result must be 'True'"); Assert.IsTrue(resultState == NetworkManagerState.Running, "The state must be 'Running'"); Assert.IsTrue(connectResult == "Success", "The connect methode must return 'Success'"); Assert.IsTrue(receivedResult == "ERROR", "The result of received message must be 'ERROR'"); }
public void ResetDisconnectedState() { if (State == NetworkManagerState.ConnectAsClientFailed || State == NetworkManagerState.ClientForciblyDisconnected || State == NetworkManagerState.HostForciblyDisconnected) { mState = NetworkManagerState.Disconnected; } }
// Event handler for PHOTON events only! public void OnEvent(EventData photonEvent) { // Load the game scene if (photonEvent.Code == 0) { Debug.Log("Photon start game event recieved!"); _lifeCycleState = NetworkManagerState.InGame; SceneManager.LoadScene(1, LoadSceneMode.Single); } }
public async Task NetworkManagerProtocolTest() { // arrange // SensorValueRawDataModel string sendMessage = NetworkProtocol.CreateMessage("{\"UID\":123,\"IsValid\":true,\"TimeStamp\":\"0001-01-01T00:00:00\",\"SensorType\":1,\"RawValue\":1234}"); NetworkManager host = new NetworkManager(5000); host.DataFormat = DataFormat.JsonObject; string resultReceived = string.Empty; host.NetworkMessageEvent += delegate(object sender, NetworkMessageEventArgs args) { resultReceived = args.Message; }; string resultShutdown = string.Empty; host.NetworkMessageShutdownEvent += delegate(object sender, NetworkMessageEventArgs args) { resultShutdown = args.Message; throw new Exception(resultShutdown); }; Stopwatch sw = new Stopwatch(); sw.Start(); StringBuilder sbStateMessages = new StringBuilder(); host.NetworkLogEvent += delegate(string stateMessage) { sbStateMessages.AppendLine($"{stateMessage}, Time: {sw.ElapsedMilliseconds}ms"); }; NetworkManagerClient client = new NetworkManagerClient(); // act bool resultStart = host.Start(); NetworkManagerState resultState = host.State; string connectResult = client.Connect(5000); client.Send(Encoding.UTF8.GetBytes(sendMessage)); await Task.Delay(1000); // assert sw.Stop(); Assert.IsTrue(resultStart, "Start result must be 'True': " + sbStateMessages.ToString()); Assert.IsTrue(resultState == NetworkManagerState.Running, "The state must be 'Running'"); Assert.IsTrue(connectResult == "Success", "The connect methode must return 'Success'"); Assert.IsTrue(resultReceived == sendMessage, "Received message must the same of sended message."); }
private void Awake() { // This manager will be needed at both the main menu and inside the game DontDestroyOnLoad(gameObject); if (instance == null) { instance = this; } else if (instance != this) { Debug.Log("Found an existing instance of the NetworkManager, destroying this one"); DestroyImmediate(this); } _lifeCycleState = NetworkManagerState.InMenu; }
public void Host() { // the host is always computer 0 mComputerID = 0; // and whenever we host, next IDs should be reset: nextComputerID = 1; mState = NetworkManagerState.AwaitingClient; if (local.IsBound == false) { IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Any, 9050); local.Bind(iep); } local.Listen(10); }
public void Disconnect() { if (remote != null && remote.Connected) { remote.Shutdown(SocketShutdown.Both); remote.Disconnect(false); mState = NetworkManagerState.Disconnected; try { local.Shutdown(SocketShutdown.Both); local.Disconnect(false); } catch { // no big deal - already disconnected } } else if (State == NetworkManagerState.AwaitingClient) { mState = NetworkManagerState.Disconnected; } }
public NetworkManager() { mFrameSentPackets = new List<string>(); mComputerName = Dns.GetHostName(); #if FRB_MDX localIP = Dns.GetHostByName(mComputerName); #else localIP = Dns.GetHostEntry(mComputerName); #endif mReceivedText = new List<string>(); mReceivedBytes = new List<Byte[]>(); mReceivedPackets = new List<BasePacket>(); local = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); localControlledSprites = new List<NetSprite>(); remoteControlledSprites = new List<NetSprite>(); pendingAddRemoteSprites = new List<NetSprite>(); mState = NetworkManagerState.Disconnected; mComputerID = 0; connectedTo = new List<int>(); mNamesConnectedTo = new List<string>(); mDelayedByteArrays = new List<DelayedByteArray>(); dataToSend = new MemoryStream(); }
public void Connect(string ipAddress) { try { mState = NetworkManagerState.AttemptingConnection; IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), 9050); remote = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); remote.SetSocketOption( System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, 1); remote.Connect(iep); mNamesConnectedTo.Add(""); connectedTo.Add(0); mState = NetworkManagerState.ConnectedAsClient; MemoryStream ms = new MemoryStream(); ms.Write(BitConverter.GetBytes(1 + this.mComputerName.Length), 0, 4); ms.WriteByte((byte)('N')); ms.Write(Encoding.ASCII.GetBytes(mComputerName), 0, mComputerName.Length); remote.Send(ms.ToArray(), (int)ms.Length, 0); } catch(Exception ) { mState = NetworkManagerState.ConnectAsClientFailed; } }
public void Activity() { #region Awaiting client if (mState == NetworkManagerState.AwaitingClient) { if (local.Poll(2000, SelectMode.SelectRead)) { remote = local.Accept(); remote.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, 1); mState = NetworkManagerState.ConnectedAsHost; MemoryStream ms = new MemoryStream(); // the size of the packet always goes first ms.Write(BitConverter.GetBytes(5), 0, 4); // then the identifier ms.WriteByte((byte)('I')); // then the contents ms.Write(BitConverter.GetBytes(this.nextComputerID), 0, 4); // finally, send it on its way remote.Send(ms.ToArray(), (int)ms.Length, 0); ms = new MemoryStream(); ms.Write(BitConverter.GetBytes(1 + this.mComputerName.Length), 0, 4); ms.WriteByte((byte)('N')); ms.Write(Encoding.ASCII.GetBytes(mComputerName), 0, mComputerName.Length); remote.Send(ms.ToArray(), (int)ms.Length, 0); mNamesConnectedTo.Add(""); this.connectedTo.Add(nextComputerID); nextComputerID++; } } #endregion #region connected as a host else if (mState == NetworkManagerState.ConnectedAsHost) { if (remote.Poll(400, SelectMode.SelectRead)) { try { int recv = remote.Receive(data); if (recv == 0) { mState = NetworkManagerState.Disconnected; remote.Close(); } else { int location = 0; while (BitConverter.ToInt32(data, location) != 0) { this.DecodeData(data, location + 4, BitConverter.ToInt32(data, location), 1); location += BitConverter.ToInt32(data, location) + 4; } } } catch (SocketException e) { switch (e.ErrorCode) { case 10054: mState = NetworkManagerState.ClientForciblyDisconnected; break; } string s = e.ToString(); } } } #endregion #region connected as a client else if (mState == NetworkManagerState.ConnectedAsClient) { if (remote.Poll(400, SelectMode.SelectRead)) { int recv = 0; try { recv = remote.Receive(data); } catch { recv = 0; } if (recv == 0) // this occurs when the host disconnects or when the connection is lost { mState = NetworkManagerState.HostForciblyDisconnected; try { remote.Shutdown(SocketShutdown.Both); remote.Disconnect(false); } catch { // if we fail here, no big deal. We're already disconnected } } else { int location = 0; List <string> actionsPerformed = new List <string>(); try { while (BitConverter.ToInt32(data, location) != 0) { actionsPerformed.Add( this.DecodeData(data, location + 4, BitConverter.ToInt32(data, location), 0)); location += BitConverter.ToInt32(data, location) + 4; if (location > recv) { StreamWriter sr = new StreamWriter("netManErrorDecodeData.txt"); sr.WriteLine("Tried to read beyond the end of the data"); sr.WriteLine(actionsPerformed[actionsPerformed.Count - 1]); sr.Close(); break; } } // at this point, the location should equal the received amount if (location != recv) { StreamWriter sr = new StreamWriter("netManErrorDecodeData.txt"); sr.WriteLine("Didn't receive data to fill all of the actions."); foreach (string s in actionsPerformed) { sr.WriteLine(s); } sr.Close(); } } catch (Exception e) { StreamWriter sr = new StreamWriter("netManErrorDecodeData.txt"); sr.Write("Error trying to decode data received from remote computer. \n"); sr.Write(e.ToString()); sr.WriteLine(); sr.WriteLine("Actions performed: "); foreach (String s in actionsPerformed) { sr.WriteLine(" " + s); } sr.WriteLine(); sr.WriteLine("data length" + data.Length); sr.Write("data: " + data + "\n\n\n"); sr.WriteLine("location: " + location); sr.Close(); } } } } #endregion #region General Activity when connected if (IsConnected) { #region Is there buffered data to send? if (dataToSend.Length != 0) { if (AdditionalLag != 0) { mDelayedByteArrays.Add(new DelayedByteArray( dataToSend.ToArray(), (TimeManager.CurrentTime + AdditionalLag))); } else { try { remote.Send(dataToSend.ToArray(), (int)dataToSend.Length, 0); } catch (SocketException) { Disconnect(); } } dataToSend = new MemoryStream(); mFrameSentPackets.Clear(); } #endregion #region See if it's time to send off the delayed packets. while (mDelayedByteArrays.Count != 0 && mDelayedByteArrays[0].TimeToSend < TimeManager.CurrentTime) { remote.Send(mDelayedByteArrays[0].ByteArray, mDelayedByteArrays[0].ByteArray.Length, 0); mDelayedByteArrays.RemoveAt(0); } #endregion #region See if pinging is enabled and it's time to ping if (mPingingEnabled && TimeManager.CurrentTime - mTickLastPingSent > .5f) { SendPing(); } #endregion } #endregion }
public void Disconnect() { if (remote != null && remote.Connected) { remote.Shutdown(SocketShutdown.Both); remote.Disconnect(false); mState = NetworkManagerState.Disconnected; try { local.Shutdown(SocketShutdown.Both); local.Disconnect(false); } catch { // no big deal - already disconnected } } else if (State == NetworkManagerState.AwaitingClient) mState = NetworkManagerState.Disconnected; }
public void Host() { // the host is always computer 0 mComputerID = 0; // and whenever we host, next IDs should be reset: nextComputerID = 1; mState = NetworkManagerState.AwaitingClient; if (local.IsBound == false) { IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Any, 9050); local.Bind(iep); } local.Listen(10); }
public void Activity() { #region Awaiting client if(mState == NetworkManagerState.AwaitingClient) { if(local.Poll(2000, SelectMode.SelectRead)) { remote = local.Accept(); remote.SetSocketOption( System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, 1); mState = NetworkManagerState.ConnectedAsHost; MemoryStream ms = new MemoryStream(); // the size of the packet always goes first ms.Write(BitConverter.GetBytes(5), 0, 4); // then the identifier ms.WriteByte((byte)('I')); // then the contents ms.Write(BitConverter.GetBytes(this.nextComputerID), 0, 4); // finally, send it on its way remote.Send(ms.ToArray(), (int)ms.Length, 0); ms = new MemoryStream(); ms.Write(BitConverter.GetBytes(1 + this.mComputerName.Length), 0, 4); ms.WriteByte((byte)('N')); ms.Write(Encoding.ASCII.GetBytes(mComputerName), 0, mComputerName.Length); remote.Send(ms.ToArray(), (int)ms.Length, 0); mNamesConnectedTo.Add(""); this.connectedTo.Add(nextComputerID); nextComputerID++; } } #endregion #region connected as a host else if(mState == NetworkManagerState.ConnectedAsHost) { if(remote.Poll(400, SelectMode.SelectRead)) { try { int recv = remote.Receive(data); if (recv == 0) { mState = NetworkManagerState.Disconnected; remote.Close(); } else { int location = 0; while (BitConverter.ToInt32(data, location) != 0) { this.DecodeData(data, location + 4, BitConverter.ToInt32(data, location), 1); location += BitConverter.ToInt32(data, location) + 4; } } } catch (SocketException e) { switch (e.ErrorCode) { case 10054: mState = NetworkManagerState.ClientForciblyDisconnected; break; } string s = e.ToString(); } } } #endregion #region connected as a client else if(mState == NetworkManagerState.ConnectedAsClient) { if(remote.Poll(400, SelectMode.SelectRead)) { int recv = 0; try { recv = remote.Receive(data); } catch { recv = 0; } if (recv == 0) // this occurs when the host disconnects or when the connection is lost { mState = NetworkManagerState.HostForciblyDisconnected; try { remote.Shutdown(SocketShutdown.Both); remote.Disconnect(false); } catch { // if we fail here, no big deal. We're already disconnected } } else { int location = 0; List<string> actionsPerformed = new List<string>(); try { while (BitConverter.ToInt32(data, location) != 0) { actionsPerformed.Add( this.DecodeData(data, location + 4, BitConverter.ToInt32(data, location), 0)); location += BitConverter.ToInt32(data, location) + 4; if (location > recv) { StreamWriter sr = new StreamWriter("netManErrorDecodeData.txt"); sr.WriteLine("Tried to read beyond the end of the data"); sr.WriteLine(actionsPerformed[actionsPerformed.Count - 1]); sr.Close(); break; } } // at this point, the location should equal the received amount if (location != recv) { StreamWriter sr = new StreamWriter("netManErrorDecodeData.txt"); sr.WriteLine("Didn't receive data to fill all of the actions."); foreach (string s in actionsPerformed) sr.WriteLine(s); sr.Close(); } } catch (Exception e) { StreamWriter sr = new StreamWriter("netManErrorDecodeData.txt"); sr.Write("Error trying to decode data received from remote computer. \n"); sr.Write(e.ToString()); sr.WriteLine(); sr.WriteLine("Actions performed: "); foreach (String s in actionsPerformed) sr.WriteLine(" " + s); sr.WriteLine(); sr.WriteLine("data length" + data.Length); sr.Write("data: " + data + "\n\n\n"); sr.WriteLine("location: " + location); sr.Close(); } } } } #endregion #region General Activity when connected if (IsConnected) { #region Is there buffered data to send? if (dataToSend.Length != 0) { if (AdditionalLag != 0) { mDelayedByteArrays.Add(new DelayedByteArray( dataToSend.ToArray(), (TimeManager.CurrentTime + AdditionalLag))); } else { try { remote.Send(dataToSend.ToArray(), (int)dataToSend.Length, 0); } catch (SocketException ) { Disconnect(); } } dataToSend = new MemoryStream(); mFrameSentPackets.Clear(); } #endregion #region See if it's time to send off the delayed packets. while (mDelayedByteArrays.Count != 0 && mDelayedByteArrays[0].TimeToSend < TimeManager.CurrentTime) { remote.Send(mDelayedByteArrays[0].ByteArray, mDelayedByteArrays[0].ByteArray.Length, 0); mDelayedByteArrays.RemoveAt(0); } #endregion #region See if pinging is enabled and it's time to ping if (mPingingEnabled && TimeManager.CurrentTime - mTickLastPingSent > .5f) SendPing(); #endregion } #endregion }
public void ResetDisconnectedState() { if (State == NetworkManagerState.ConnectAsClientFailed || State == NetworkManagerState.ClientForciblyDisconnected || State == NetworkManagerState.HostForciblyDisconnected) mState = NetworkManagerState.Disconnected; }