static void EventLoop(UdpSocket socket) { UdpConnection c = null; while (true) { UdpEvent ev = default(UdpEvent); if (socket.Poll(ref ev)) { UdpLog.User(ev.EventType.ToString()); switch (ev.EventType) { case UdpEventType.ConnectRequest: socket.Accept(ev.EndPoint); break; case UdpEventType.Connected: c = ev.Connection; break; } } if (c != null) { c.Send(10u); } Thread.Sleep(100); } }
static void Client() { UdpSocket client = UdpSocket.Create <UdpPlatformManaged, DummySerializer>(); client.Start(UdpEndPoint.Any); client.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); while (true) { UdpEvent ev = default(UdpEvent); while (client.Poll(ref ev)) { UdpLog.User("Event raised {0}", ev.EventType); switch (ev.EventType) { case UdpEventType.Connected: UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint); break; #if DISABLE_AUTO_ACCEPT case UdpEventType.ConnectFailed: UdpLog.User("Connection to {0} failed", ev.EndPoint); break; #endif } } // Simulate ~60fps game loop Thread.Sleep(16); } }
public void SendOutBound(UdpEvent udp_event) { if (this.is_enable_discovery && this.message_sender != null) { this.message_sender.Accept(udp_event); } }
public bool Process() { UdpEvent ev = default(UdpEvent); ConnectionObject co = null; pair val = default(pair); if (socket.Poll(ref ev)) { switch (ev.EventType) { case UdpEventType.Connected: ev.Connection.UserToken = co = new ConnectionObject(); co.connection = ev.Connection; connections.Add(ev.Connection); for (int i = 0; i < 16; ++i) { co.QueueNext(); co.Send(); } break; case UdpEventType.ObjectLost: val = (pair)ev.Object; co = (ConnectionObject)ev.Connection.UserToken; co.Nack(val); co.Send(); break; case UdpEventType.ObjectDelivered: val = (pair)ev.Object; co = (ConnectionObject)ev.Connection.UserToken; co.Ack(val); co.QueueNext(); co.Send(); break; case UdpEventType.ObjectReceived: val = (pair)ev.Object; co = (ConnectionObject)ev.Connection.UserToken; co.Recv(val); co.DequeueReceived(); break; case UdpEventType.ObjectRejected: Console.WriteLine("REJECTED"); break; case UdpEventType.ObjectSendFailed: Console.WriteLine("SENDFAILED"); break; } return(true); } return(false); }
internal void OnEventConnectionOption(UdpEvent ev) { switch (ev.Option) { case UdpConnectionOption.AlwaysSendMtu: alwaysSendMtu = ev.OptionIntValue == 1; break; } }
public void Loop() { UdpEvent ev = default(UdpEvent); while (true) { while (socket.Poll(ref ev)) { switch (ev.EventType) { case UdpEventType.Connected: // log in local console UdpLog.User("Client connected from {0}, total clients {1}", ev.Connection.RemoteEndPoint, socket.ConnectionCount); // send welcome message ev.Connection.Send("Welcome to the chat server!"); // send message to all other clients SendToAllClients("Client connected from {0}", ev.Connection.RemoteEndPoint); // add to client list clients.Add(ev.Connection); break; case UdpEventType.Disconnected: // log in local console UdpLog.User("Client at {0} disconnected, total clients {1}", ev.Connection.RemoteEndPoint, socket.ConnectionCount); // remove from client list clients.Remove(ev.Connection); // Send message to all others SendToAllClients("Client at {0} disconnected", ev.Connection.RemoteEndPoint); break; // When we receive, just forward to all clients case UdpEventType.ObjectReceived: SendToAllClients(ev.Object as string); break; // If lost, resend to connection it was lost on case UdpEventType.ObjectLost: ev.Connection.Send(ev.Object); break; } } // Simulate ~60fps game loop Thread.Sleep(16); } }
public void Loop() { UdpEvent ev = default(UdpEvent); StreamReader input = new StreamReader(Console.OpenStandardInput()); Char[] buffer = new Char[1024]; ReadLine read = Console.ReadLine; IAsyncResult result = null; UdpConnection connection = null; while (true) { while (socket.Poll(ref ev)) { switch (ev.EventType) { case UdpEventType.Connected: UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint); connection = ev.Connection; break; case UdpEventType.Disconnected: UdpLog.User("Disconnected from server at {0}", ev.Connection.RemoteEndPoint); connection = null; break; case UdpEventType.ObjectReceived: Console.WriteLine(": " + (ev.Object as string)); break; } } if (result == null) { result = read.BeginInvoke(null, null); } if (result.IsCompleted) { if (connection != null) { connection.Send(read.EndInvoke(result)); } result = read.BeginInvoke(null, null); } // Simulate ~60fps game loop Thread.Sleep(16); } }
void Update() { UdpEvent ev = default(UdpEvent); while (socket.Poll(ref ev)) { switch (ev.EventType) { case UdpEventType.Connected: UdpLog.User("Client connect from {0}", ev.Connection.RemoteEndPoint); break; } } }
private void ProcessConnect(UdpEvent ev) { if (ev.Connection != null) { LoggerManager.Instance.Debug("ProcessConnect connect to server remote {0} result {1}", ev.Connection.RemoteEndPoint, ev.EventType); } else { LoggerManager.Instance.Debug("ProcessConnect connect to server result {0}", ev.EventType); } if (ev.EventType == UdpEventType.Connected) { object obj = statusLock; Monitor.Enter(obj); try { connectionStatus = ConnectionStatus.Connected; } finally { Monitor.Exit(obj); } connection = ev.Connection; if (handlerPipeline.InHeader != null) { handlerPipeline.InHeader.OnConnected(this, SocketError.Success); } } else { object obj = statusLock; Monitor.Enter(obj); try { connectionStatus = ConnectionStatus.Disconnected; } finally { Monitor.Exit(obj); } if (handlerPipeline.InHeader != null) { handlerPipeline.InHeader.OnConnected(this, SocketError.SocketError); } } }
public void HandlerEvent(UdpEvent udp_event) { Message message = udp_event.Message; IPEndPoint sender = udp_event.Address; Node node = new Node(message.From.Id, sender.Address.ToString(), sender.Port); if (this.is_inbound_known_node && !ContainNodeHandler(node)) { Logger.Warning( string.Format("Receive packet from unknown node {0}.", sender.Address.ToString())); return; } NodeHandler handler = GetNodeHandler(node); handler.NodeStatistics.MessageStatistics.AddUdpInMessage(message.Type); switch (message.Type) { case UdpMessageType.DISCOVER_PING: { handler.HandlePing((PingMessage)message); } break; case UdpMessageType.DISCOVER_PONG: { handler.HandlePong((PongMessage)message); } break; case UdpMessageType.DISCOVER_FIND_NODE: { handler.HandleFindNode((FindNodeMessage)message); } break; case UdpMessageType.DISCOVER_NEIGHBORS: { handler.HandleNeighbours((NeighborsMessage)message); } break; default: break; } }
public void HandlerEvent(UdpEvent udp_event) { IPEndPoint sender = udp_event.Address; if (udp_event.Message.Type != UdpMessageType.BACKUP_KEEP_ALIVE) { Logger.Warning( string.Format("Receive not keep alive message from {0}, type {1}", sender.Address.ToString(), udp_event.Message.Type)); return; } if (!this.members.Contains(sender.Address.ToString())) { Logger.Warning( string.Format("Receive keep alive message from {0} is not my member.", sender.Address.ToString())); return; } this.last_keep_alive_time = Helper.CurrentTimeMillis(); KeepAliveMessage message = (KeepAliveMessage)udp_event.Message; string ip = sender.Address.ToString(); if (this.status == BackupStatus.INIT && (message.Flag || message.Priority > this.priority)) { this.status = BackupStatus.SLAVER; return; } if (this.status == BackupStatus.MASTER && message.Flag) { if (message.Priority > priority) { this.status = BackupStatus.SLAVER; } else if (message.Priority == priority && this.local_ip.CompareTo(ip) < 0) { this.status = BackupStatus.SLAVER; } } }
private void ProcessReceive(UdpEvent ev) { if (ev.EventType == UdpEventType.StreamDataReceived) { byte[] data = ev.StreamOp.Data; int size = ev.StreamOp.Data.Length; if (handlerPipeline.InHeader != null) { try { handlerPipeline.InHeader.OnReceived(this, data, 0, size); } catch (Exception ex) { LoggerManager.Instance.Error("ProcessReceive " + ex.ToString()); } } } }
private void ProcessServerForceQuit(UdpEvent ev) { LoggerManager.Instance.Debug("ProcessServerForceQuit server {0} force quit me", ev.Connection.RemoteEndPoint); lastConnection = null; if (handlerPipeline.InHeader != null) { handlerPipeline.InHeader.OnDisconnected(this, SocketError.ConnectionAborted); } object obj = statusLock; Monitor.Enter(obj); try { connectionStatus = ConnectionStatus.Disconnected; } finally { Monitor.Exit(obj); } }
static void Server() { #if DISABLE_AUTO_ACCEPT UdpConfig config = new UdpConfig(); config.AutoAcceptIncommingConnections = false; #else UdpConfig config = new UdpConfig(); #endif UdpSocket server = UdpSocket.Create <UdpPlatformManaged, DummySerializer>(config); server.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000)); while (true) { UdpEvent ev = default(UdpEvent); while (server.Poll(ref ev)) { UdpLog.User("Event raised {0}", ev.EventType); switch (ev.EventType) { case UdpEventType.Connected: UdpLog.User("Client connected from {0}, total clients connected: {1}", ev.Connection.RemoteEndPoint, server.ConnectionCount); break; #if ENABLE_MANUAL_ACCEPT case UdpEventType.ConnectRequest: UdpLog.User("Connection requested from {0}", ev.EndPoint); server.Accept(ev.EndPoint); break; #endif } } // Simulate ~60fps game loop Thread.Sleep(16); } }
public bool Poll(ref UdpEvent ev) { bool allowRestart = (index != 0); RESTART: for (int i = index; i < sockets.Length; ++i) { if (sockets[i].Poll(ref ev)) { index = i + 1; return(true); } } if (allowRestart) { index = 0; allowRestart = false; goto RESTART; } return(false); }
private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { try { //Read the message that was received from the UDP echo client. Stream streamIn = args.GetDataStream().AsStreamForRead(); StreamReader reader = new StreamReader(streamIn); string jsonData = await reader.ReadToEndAsync(); //Debug.Log("MESSAGE: " + jsonData); //UnityEngine.Debug.LogError(jsonData); DataStruct newData = Newtonsoft.Json.JsonConvert.DeserializeObject<DataStruct>(jsonData); UdpEvent.onDataRecieved(newData); } catch (Exception e) { Exception mye = e; String tst = mye.Message; string sts = ""; } }
/// <summary> /// The method, intended to be threaded as it is blocking, for recieving udp messages from clients, /// and sending them to the parser /// </summary> private void RecieveUdp() { IPHostEntry localHostEntry; try { localHostEntry = Dns.GetHostEntry(Dns.GetHostName()); } catch (Exception) { AddText("Local Host not found"); // fail return; } IPAddress localIp = null; foreach (IPAddress ip in localHostEntry.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) localIp = ip; } _localEndPoint = new IPEndPoint(localIp, 48484); while (IsRunning) { try { Byte[] received = new Byte[512]; IPEndPoint tmpIpEndPoint = new IPEndPoint(localIp, 48484); EndPoint remoteEp = (tmpIpEndPoint); int bytesReceived = _udpSocket.ReceiveFrom(received, ref remoteEp); String dataReceived = System.Text.Encoding.UTF8.GetString(received); if (UdpMessageEvent != null) { UdpEvent udpE = new UdpEvent(); udpE.Message = dataReceived.Replace("\0", ""); udpE.Address = remoteEp; UdpMessageEvent(this, udpE); } }catch(Exception e) { AddTextFromThread("Message recieve exception: " +e.ToString()); } } }
/// <summary> /// The parser for the udp messages. /// </summary> /// <param name="sender">The sender is the object sending the event </param> /// <param name="e">The udp event including the address of the sender </param> private void UdpMessageListener(object sender, UdpEvent e) { AddTextFromThread("New message from: " + e.Address); AddTextFromThread("Contents: " + e.Message); Player p = null; if( PlayerList.AddressLookup.ContainsKey(e.Address.ToString()) ) { p = PlayerList.PlayerArray[PlayerList.AddressLookup[e.Address.ToString()]]; } String[] messageArray = e.Message.Split(' '); switch (messageArray[0]) { case "JOIN": if (GameState == 0) { AddTextFromThread("Player added: " + PlayerList.AddPlayer(e.Address,e.Message.Remove(0,5)).ToString()); foreach( Player player in PlayerList.PlayerArray) { SendToPlayer(player, "PLAYERNUMBER " + player.PlayerNumber ); } SendPlayerList(); SendToAllPlayers("LOBBY"); } else if( GameState == -2 ) { AddTextFromThread("Player joined: " + PlayerList.AddPlayer(e.Address, e.Message.Remove(0, 5)).ToString()); foreach (Player player in PlayerList.PlayerArray) { SendToPlayer(player, "PLAYERNUMBER " + player.PlayerNumber); } SendPlayerList(); _usersConnected.PlayerJoined(PlayerList.AddressLookup[e.Address.ToString()]); SendPlayerList(); } break; case "CARD": PlayerPlayedCard( p, int.Parse( messageArray[1] ), messageArray); SendToAllPlayers("ANIMATION CARDSFROM " + p.PlayerNumber + " 1"); break; case "DRAWCARD": DownDeck.Peek().OnDraw(this, p, messageArray); break; case "MOOSE": if( GameState == 4) DoMoose(p); break; case "CARDARGS": if(GameState == 3) WaitingCard.TargetedAction(this,messageArray); else if(GameState == 0) { if (_playerSwap == -1) { _playerSwap = int.Parse(messageArray[1]); SendToAllPlayers("LOBBY"); } else { PlayerList.SwapPlayer(_playerSwap, int.Parse(messageArray[1])); _playerSwap = -1; SendToAllPlayers("LOBBY"); } } break; case "LIGHTON": PlayerList.PlayerLight(p); break; case "ANNOUNCE": SendAnnounce(e.Message.Remove(0,8)); break; case "DRINKRESET": SendToAllPlayers(String.Format("SETDRINK {0} 0",p.PlayerNumber.ToString())); break; case "DRUNK": SendPlayerDrinks(p, -1); break; case "STARTDRINK": SendToAllPlayers("STARTDRINK " + p.PlayerNumber); break; case "DRINKSFORM": SendToAllPlayers("TIMEDFORM " + messageArray[1] + " " + p.PlayerNumber + " Too many drinks backed up for " + p.Name + "!!"); break; } }
internal void OnEventConnectionOption(UdpEvent ev) { switch (ev.Option) { case UdpConnectionOption.AlwaysSendMtu: alwaysSendMtu = ev.OptionIntValue == 1; break; case UdpConnectionOption.MtuSize: mtu = UdpMath.Clamp(ev.OptionIntValue, socket.Config.MtuMin, socket.Config.MtuMax); break; } }