public Connect(string ip, int port, NetworkProtocol protocol) { IPAddress address; if (!IPAddress.TryParse(ip, out address)) { throw new InvalidCastException("IP 格式錯誤,請輸入正確的 IPV4 IP ex : 35.123.123.123"); } string ServerIP = address.ToString() + ":" + port; NetworkProtocol = protocol; gameService = new GameNetworkService(NetworkProtocol); //websocket 的地址,對應到伺服器 websocketsharp 開出的地址 if (NetworkProtocol == NetworkProtocol.WebSocket) { gameService.Address = string.Format("ws://{0}/WebSocket", ServerIP); } else { gameService.Address = ServerIP; } _system = new _System(); AddCallBackHandler(255, _system); }
public void Initialize(NetworkProtocol protocol) { _Protocal = protocol; this.MessagePacker = new SerializerPacker(); this.MessageDispatcher = new ClientDispatcher(); try { switch (protocol) { case NetworkProtocol.KCP: this.Service = new KService(); break; case NetworkProtocol.TCP: this.Service = new TService(); break; default: throw new ArgumentOutOfRangeException(); } this.Service.AcceptCallback += this.OnAccept; this.StartAccept(); } catch (Exception e) { throw new Exception($"{e}"); } }
/// <summary>验证数据,通过抛出异常的方式提示验证失败。</summary> /// <param name="isNew">是否插入</param> public override void Valid(Boolean isNew) { // 如果没有脏数据,则不需要进行任何处理 if (!HasDirty) { return; } // 自动生成产品证书密钥 if (Code.IsNullOrEmpty()) { Code = Rand.NextString(8); } if (Secret.IsNullOrEmpty()) { Secret = Rand.NextString(16); } if (Kind.IsNullOrEmpty()) { Kind = "设备"; } if (Category.IsNullOrEmpty()) { Category = "边缘网关"; } if (DataFormat.IsNullOrEmpty()) { DataFormat = "Json"; } if (NetworkProtocol.IsNullOrEmpty()) { NetworkProtocol = "以太网"; } }
public void Initialize(NetworkProtocol protocol, IPEndPoint ipEndPoint) { _Protocal = protocol; try { switch (protocol) { case NetworkProtocol.KCP: this.Service = new KService(ipEndPoint); break; case NetworkProtocol.TCP: this.Service = new TService(ipEndPoint); break; default: throw new ArgumentOutOfRangeException(); } this.Service.AcceptCallback += this.OnAccept; this.StartAccept(); } catch (Exception e) { throw new Exception($"{ipEndPoint}", e); } }
public void Awake(NetworkProtocol protocol, IPEndPoint ipEndPoint) { try { switch (protocol) { case NetworkProtocol.TCP: this.Service = new TService(ipEndPoint); break; case NetworkProtocol.KCP: this.Service = new KService(ipEndPoint); break; default: throw new ArgumentOutOfRangeException(); } this.StartAccept(); } catch (Exception e) { throw new Exception($"{ipEndPoint}", e); } }
public void Awake(NetworkProtocol protocol) { try { switch (protocol) { case NetworkProtocol.KCP: this.Service = new KService() { Parent = this }; break; case NetworkProtocol.TCP: this.Service = new TService() { Parent = this }; break; case NetworkProtocol.WebSocket: this.Service = new WService() { Parent = this }; break; } } catch (Exception e) { throw new Exception($"{e}"); } }
public void Awake(NetworkProtocol protocol, int packetSize = Packet.PacketSizeLength2) { switch (protocol) { case NetworkProtocol.KCP: this.Service = new KService() { Parent = this }; break; case NetworkProtocol.TCP: this.Service = new TService(packetSize) { Parent = this }; break; case NetworkProtocol.WebSocket: this.Service = new WService() { Parent = this }; break; } }
public void Initialize(NetworkProtocol rProtocol, IPEndPoint rIpEndPoint) { try { switch (rProtocol) { case NetworkProtocol.TCP: this.mService = new TService(rIpEndPoint); break; case NetworkProtocol.KCP: this.mService = new KService(rIpEndPoint); break; default: throw new ArgumentOutOfRangeException(); } this.StartAccept(); } catch (Exception e) { throw new Exception($"{rIpEndPoint}", e); } }
/// <summary> /// 初始化 /// </summary> /// <param name="protocol">通讯协议 TCP ? KCP ? WEB?</param> /// <param name="address">本地IP地址</param> public void Awake(NetworkProtocol protocol, string address) { try { IPEndPoint ipEndPoint; switch (protocol) { case NetworkProtocol.KCP: ipEndPoint = NetworkHelper.ToIPEndPoint(address); this.Service = new KService(ipEndPoint, this.OnAccept); //传过去 得到客户端AChannel的回调 break; case NetworkProtocol.TCP: ipEndPoint = NetworkHelper.ToIPEndPoint(address); this.Service = new TService(ipEndPoint, this.OnAccept); break; case NetworkProtocol.WebSocket: string[] prefixs = address.Split(';'); this.Service = new WService(prefixs, this.OnAccept); break; } } catch (Exception e) { throw new Exception($"NetworkComponent Awake Error {address}", e); } }
public void Awake(NetworkProtocol protocol) { this.networkProtocol = protocol; string[] ips = NetHelper.GetAddressIPs(); StartConfig[] startConfigs = StartConfigComponent.Instance.GetAll(); foreach (StartConfig startConfig in startConfigs) { Game.Scene.GetComponent <TimerComponent>().WaitAsync(100); if (!ips.Contains(startConfig.ServerIP) && startConfig.ServerIP != "*") { continue; } if (startConfig.AppType.Is(AppType.Manager)) { continue; } StartProcess(startConfig.AppId); } this.WatchProcessAsync(); }
//accept(address i.e. 127.0.0.1:10002) public BaseNetwork(NetworkProtocol protocol, string address, IMessagePacker msgPacker, int packetSize = Packet.PacketSizeLength4) { _msgPacker = msgPacker; _sessions = new Dictionary <long, NetworkSession>(); try { IPEndPoint ipEndPoint; switch (protocol) { case NetworkProtocol.TCP: ipEndPoint = NetworkHelper.ToIPEndPoint(address); _service = new TService(packetSize, ipEndPoint, channel => { OnAccept(channel); }); break; case NetworkProtocol.WebSocket: var prefixes = address.Split(';'); _service = new WService(prefixes, channel => { OnAccept(channel); }); break; } } catch (Exception e) { throw new Exception($"NetworkComponent Awake Error {address}", e); } }
internal string DetermineServiceURL() { string url; if (this.RegionEndpoint == null) { url = this.ServiceURL; } else { var endpoint = this.RegionEndpoint.GetEndpointForService(this.RegionEndpointServiceName); string protocol; if (this.Protocol == NetworkProtocol.HTTP && endpoint.HTTP) { protocol = "http://"; } else { protocol = "https://"; } url = new Uri(string.Concat(protocol, endpoint.Hostname)).AbsoluteUri; } return(url); }
public void NetworkProtocolCreateResponseSimpleTest() { // arrange // is the date valid bool isValid = true; // count of passing this data short passing = 1; // the unique id of packet long uid = 123; // the length of incoming json data. int receivedMessageLength = 4; // the datetime create from DateTime dt = DateTime.Now; // act string result = NetworkProtocol.CreateResponseMessage(isValid, passing, uid, receivedMessageLength, dt); // assert string[] sa = result.Split('\r', '\n').Where(w => !string.IsNullOrEmpty(w)).Select(s => s).ToArray(); Assert.AreEqual(sa[0], "RESPONSE: VALID"); Assert.AreEqual(sa[1], "RECEIVED PASSING: 1"); Assert.AreEqual(sa[2], $"RECEIVED DATETIME: {this.GetDateTimeFormat(dt)}"); Assert.AreEqual(sa[3], "RECEIVED UID: 123"); Assert.AreEqual(sa[4], "RECEIVED LENGTH: 4"); }
void OnNetworkMessage(byte[] udpMessage, IPEndPoint remoteEndPoint) { int _appIdentifier; byte _messageType; string _senderGuid; if (!NetworkProtocol.TryParseBasicInfo(udpMessage, out _appIdentifier, out _messageType)) { return; } if (_appIdentifier != APP_IDENTIFIER) { return; } switch (_messageType) { case (int)NetworkMessageType.LobbyMessage: LobbyMessage lobbyMessage = new LobbyMessage(); lobbyMessage.Parse(udpMessage); ProcessLobbyMessage(lobbyMessage, remoteEndPoint); break; default: ThreadSafeLog("unkown message type: " + _messageType); break; } }
/// <summary> /// Instantiates network streaming definition. This constructor can /// be used with only with <see cref="NetworkProtocol.RTP"/> value of protocol parameter. /// </summary> /// <param name="protocol">Protocol to use.</param> /// <param name="ip">Ip address to use.</param> /// <param name="port">Port to use.</param> /// <param name="rtpPortAudio">Port to use for audio.</param> /// <param name="rtpPortVideo">Port to use for video.</param> /// <exception cref="ArgumentException"><see cref="protocol"/> is not RTP.</exception> public OutputNetworkStream(NetworkProtocol protocol, string ip, ushort port, ushort rtpPortAudio, ushort rtpPortVideo) : this(protocol, ip, port) { // this.rtpPortAudio = rtpPortAudio; this.rtpPortVideo = rtpPortVideo; }
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 Awake(NetworkProtocol protocol) { try { switch (protocol) { case NetworkProtocol.KCP: this.Service = new KService(); break; case NetworkProtocol.TCP: this.Service = new TService(); break; default: throw new ArgumentOutOfRangeException(); } this.Service.AcceptCallback += this.OnAccept; this.Start(); } catch (Exception e) { throw new Exception($"{e}"); } }
public void Awake(NetworkProtocol protocol, string host, int port) { try { switch (protocol) { case NetworkProtocol.TCP: this.Service = new TService(host, port); break; case NetworkProtocol.UDP: this.Service = new UService(host, port); break; default: throw new ArgumentOutOfRangeException(); } this.StartAccept(); } catch (Exception e) { throw new Exception($"{host} {port}", e); } }
private bool TryConnect(string ip, int port, string auth) { try { client = new TcpClient(ip, port); string msgStr = "CONNECT:" + auth; NetworkProtocol.Send(client, msgStr); gl.status.Connected = true; return(true); } catch (ArgumentNullException e) { client = null; gl.status.Connected = false; gl.log.WriteLine(":( CONNECT TO SERVER " + ip + " FAILED: " + e); return(false); } catch (SocketException e) // server not available { client = null; if (ip == "127.0.0.1") { gl.log.WriteLine(":) CONNECT TO LOCAL SERVER FAILED: PROBABLY NO LOCAL SERVER RUNNING, TRYING GAMELIFT"); } else { gl.log.WriteLine(":( CONNECT TO SERVER " + ip + "FAILED: " + e + " (ARE YOU ON THE *AMAZON*INTERNAL*NETWORK*?)"); } gl.status.Connected = false; return(false); } }
public void Awake(NetworkProtocol protocol) { switch (protocol) { case NetworkProtocol.KCP: this.Service = new KService() { Parent = this }; break; case NetworkProtocol.TCP: this.Service = new TService() { Parent = this }; break; case NetworkProtocol.WebSocket: this.Service = new WService() { Parent = this }; break; } }
public void InitAndConnect(IPEndPoint ip, NetworkProtocol protocol, Action connect = null) { mConnect = new Connect(ip.Address.ToString(), ip.Port, protocol); SystemHandler = new _System(); mConnect.AddCallBackHandler(_System.OperatorCode, SystemHandler); SystemHandler.Connect += connect; }
void SendUdpMessage(IPEndPoint endPoint, NetworkProtocol message) { using (UdpClient udpClient = new UdpClient()) { byte[] buffer = new byte[1000]; int length = message.ToByteArray(buffer); udpClient.Send(buffer, length, endPoint); } }
/// <summary> /// Adds the windows firewall rule. /// </summary> /// <param name="port">The port.</param> /// <param name="protocol">The protocol.</param> public void AddSystemFirewallRule(int port, NetworkProtocol protocol) { // First try to remove it so we don't end up creating duplicates RemoveSystemFirewallRule(port, protocol); var args = string.Format("advfirewall firewall add rule name=\"Port {0}\" dir=in action=allow protocol={1} localport={0}", port, protocol); RunNetsh(args); }
public void InitAndConnect(IPEndPoint ip, NetworkProtocol protocol, Action connect = null) { mConnect = new Connect(ip.Address.ToString(), ip.Port, protocol); mConnect._system.ConnectToServer(); if (connect != null) { mConnect._system.Connect += connect; } }
public NetworkClient(NetworkProtocol protocol, string ip = "127.0.0.1", int port = 1, int cmdLength = 1, int pctLength = 1024) { Ip = ip; Port = port; Protocol = protocol; CommandLength = cmdLength; PacketSize = pctLength; Connect(); }
//Send message to single client private void SendMessage(TcpClient client, SimpleMessage msg) { try { NetworkProtocol.Send(client, msg); } catch (Exception e) { this.clientsToRemove.Add(client); } }
/// <summary> /// Instantiates network streaming definition. This constructor can /// be used with any <see cref="NetworkProtocol"/> except <see cref="NetworkProtocol.RTP"/>. /// </summary> /// <param name="protocol">Protocol to use.</param> /// <param name="ip">Ip address to use.</param> /// <param name="port">Port to use.</param> /// <exception cref="ArgumentException"><see cref="protocol"/> is RTP. This constuctor does not allows defining audio and video ports separately.</exception> public OutputNetworkStream(NetworkProtocol protocol, string ip, ushort port) { if (ip == null) { throw new ArgumentNullException("ip"); } if (ip.Length == 0) { throw new ArgumentException("String is empty.", "ip"); } // this.protocol = protocol; this.ip = ip; this.port = port; }
public void Awake(NetworkProtocol protocol) { switch (protocol) { case NetworkProtocol.TCP: this.Service = new TService(); break; default: throw new ArgumentOutOfRangeException(); } }
// Called by the client to receive new messages public void Update() { if (client == null) { return; } var messages = NetworkProtocol.Receive(client); foreach (SimpleMessage msg in messages) { HandleMessage(msg); } }
void BroadcastMessage(NetworkProtocol message) { IPEndPoint broadcastEndPoint = new IPEndPoint(IPAddress.Broadcast, DEFAULT_PORT); IPEndPoint broadcastEndPoint2 = new IPEndPoint(IPAddress.Broadcast, DEBUG_PORT); using (UdpClient udpClient = new UdpClient()) { byte[] buffer = new byte[1000]; int length = message.ToByteArray(buffer); udpClient.Send(buffer, length, broadcastEndPoint); udpClient.Send(buffer, length, broadcastEndPoint2); } }
protected void Awake(NetworkProtocol protocol) { switch (protocol) { case NetworkProtocol.TCP: this.Service = new TService(); break; case NetworkProtocol.UDP: this.Service = new UService(); break; default: throw new ArgumentOutOfRangeException(); } }
public void Update() { if (client == null) { return; } var messages = NetworkProtocol.Receive(client); foreach (string msgStr in messages) { gl.log.WriteLine("Msg rcvd: " + msgStr); HandleMessage(msgStr); } }
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."); }
public NetworkClientWrapper(NetworkProtocol protocol, IPEndPoint endPoint) { isUdp = protocol == NetworkProtocol.Udp; if (isUdp) { udpClient = new UdpClient(); udpClient.ExclusiveAddressUse = false; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.Client.Bind(endPoint); } else { tcpClient = new TcpClient(endPoint); } }
protected void Awake(NetworkProtocol protocol, string host, int port) { switch (protocol) { case NetworkProtocol.TCP: this.Service = new TService(host, port); break; case NetworkProtocol.UDP: this.Service = new UService(host, port); break; default: throw new ArgumentOutOfRangeException(); } this.StartAccept(); }
/// <summary> /// 设置模块使用网络协议的命令 /// </summary> /// <param name="networkProtocol">模块使用的网络协议</param> /// <returns></returns> public Byte[] SettingModuleNetworkProtocolCommand(NetworkProtocol networkProtocol) { return GetDatagram(MessageId.SettingModuleNetworkProtocol, new Parameter(ParameterType.NetworkProtocol, (Byte)networkProtocol)); }
/// <summary> /// "Sending {0} bytes via {1} to {2} on port {3}." /// </summary> /// <returns></returns> public static LogMessage SendingRequest(int bytes, NetworkProtocol proto, System.Net.IPEndPoint ep) { return Create(Resources.LogMessages.SendingRequest, new object[] { bytes, proto, ep.Address, ep.Port }); }
internal string DetermineServiceURL() { string url; if (this.RegionEndpoint == null) { url = this.ServiceURL; } else { var endpoint = this.RegionEndpoint.GetEndpointForService(this.RegionEndpointServiceName); string protocol; if (this.Protocol == NetworkProtocol.HTTP && endpoint.HTTP) protocol = "http://"; else protocol = "https://"; url = new Uri(string.Concat(protocol, endpoint.Hostname)).AbsoluteUri; } return url; }