// Use this for initialization private void Awake() { if (instance == null || instance == this) { instance = this; } else { Destroy(this); } pic = new byte[5]; gyroData = new byte[5]; GetIPAddress(); udpClient = new UdpClient(myPort); udpClient.EnableBroadcast = true; broadcastAddr = new IPEndPoint(IPAddress.Parse("255.255.255.255"), discoverPort); Debug.Log("Broadcast client on"); any = new IPEndPoint(IPAddress.Any, myPort); UdpState s = new UdpState(); s.e = any; s.u = udpClient; Debug.Log("Any: " + any.Address + ":" + any.Port); udpClient.BeginReceive(new AsyncCallback(ReceiveDatagram), s); }
public UdpManger() { // 本机节点 localEP = new IPEndPoint(IPAddress.Any, listenPort); // 远程节点 remoteEP = new IPEndPoint(IPAddress.Any, remotePort); // 实例化 udpReceive = new UdpClient(localEP); udpSend = new UdpClient(); // 分别实例化udpSendState、udpReceiveState udpSendState = new UdpState(); udpSendState.ipEndPoint = remoteEP; udpSendState.udpClient = udpSend; udpReceiveState = new UdpState(); udpReceiveState.ipEndPoint = remoteEP; udpReceiveState.udpClient = udpReceive; //receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //receiveSocket.Bind(localEP); //sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //sendSocket.Bind(remoteEP); }
public void StopReceive() { Stop = true; try { s.u.Client.Close(); s.u.Close(); s = null; instance = null; } catch (Exception ex) { Console.WriteLine(ex.Message); } try { if (ListenerThread.IsAlive) { ListenerThread.Abort(); } ListenerThread = null; } catch { } finally { Console.WriteLine("Stoped"); } }
/// <summary> /// Parses a message to determine its type to pass it to the right handler. /// </summary> /// <param name="message"></param> /// <param name="udpState">The client the message came from.</param> public async void ProcessMessage(dynamic messageString, UdpState udpState) { ValidationResult validationResult = await Validation.ValidateMessageAsync(inputJson : messageString, objectType : typeof(Message), allowAdditionalProperties : true); if (validationResult.IsValid) { Message message = JsonConvert.DeserializeObject <Message>(messageString.ToString()); switch (message.MessageType) { case (0): Handshake(udpState); break; case (1): ProcessGameState(messageString, udpState); break; case (2): break; case (3): ProcessQueueMatchRequest(messageString, udpState); break; } } }
/// <summary> /// Start listening on udp port /// </summary> public override void Start() { Log.Debug("PortUdp.start"); try { Log.Debug("Start waiting for a connection..."); _listen = true; var ip = GetLocalIp(); var ep = new IPEndPoint(ip, _port); var u = new UdpClient(); u.EnableBroadcast = true; u.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); u.Client.Bind(ep); _state = new UdpState(); _state.e = ep; _state.u = u; u.BeginReceive(ReceiveCallback, _state); base.Start(); } catch (Exception e) { Log.Error("PortUdp.Start error", e); } }
/// <summary> /// Receives and replies to a handshake request. /// </summary> /// <param name="udpState"></param> private void Handshake(UdpState udpState) { Console.WriteLine($"Handshaking with {udpState.ServerEP.Address}..."); byte[] reply = Encoding.ASCII.GetBytes("Pong!"); udpState.UdpClient.Send(reply, reply.Length, udpState.ServerEP); }
protected void ReceiveData(IAsyncResult ar) { try { UdpState state = (UdpState)ar.AsyncState; IPEndPoint endPoint = null; byte[] buf = state.Client.EndReceive(ar, ref endPoint); state.Client.BeginReceive(ReceiveData, state); lock (IncomingMessages) { IncomingMessages.Enqueue(new IncomingMessage { EndPoint = endPoint, MessageBytes = buf }); } } catch (ObjectDisposedException) { return; } catch (Exception e) { Logger.LogError("SlMessageSystem.ReceiveData", e.ToString()); } }
public AsyncUdpClient(string ServerIP) { // 本机节点 localEP = new IPEndPoint(IPAddress.Any, listenPort); // 远程节点 remoteEP = new IPEndPoint(IPAddress.Parse(ServerIP), remotePort); // 实例化 udpReceive = new UdpClient(localEP); udpSend = new UdpClient(); // 分别实例化udpSendState、udpReceiveState udpSendState = new UdpState(); udpSendState.ipEndPoint = remoteEP; udpSendState.udpClient = udpSend; udpReceiveState = new UdpState(); udpReceiveState.ipEndPoint = remoteEP; udpReceiveState.udpClient = udpReceive; //receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //receiveSocket.Bind(localEP); //sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //sendSocket.Bind(remoteEP); }
public static async Task StartCommand() { // WORK AS CLIENT try { client_command = new UdpClient(CommandPortNumber); UdpState s = new UdpState { e = new IPEndPoint(IPAddress.None, CommandPortNumber), u = client_command }; //client_command.Connect(new IPEndPoint(IPAddress.Parse(TelloIpAddress), CommandPortNumber)); client_command.BeginReceive(new AsyncCallback(ReceiveCallback_Command), s); // Init, and set the speed to the minimum await SendCommand("command"); await SendCommand("speed 10"); await SendCommand("streamon"); IsCommandReady = true; } catch (Exception ex) { Console.WriteLine("COMMAND CLIENT INIT ERROR: " + ex.Message); } }
private void BeginReceive_UDP_Client_Callback(IAsyncResult ar) { // End the operation and display the received data on // the console. UdpClient u = ((UdpState)(ar.AsyncState)).u; IPEndPoint e = ((UdpState)(ar.AsyncState)).e; // UdpClient client = NetworkPacket NewP = new NetworkPacket(); NewP.FromByteArray(UdpClient.EndReceive(ar, ref e)); NewP.ToString(); CheckLostnotReceivedPacket(NewP.Packet_Id); Console.WriteLine(" Packet Loss Percentage : " + PacketLossPercentage() + " %"); Console.WriteLine(NewP.ToString() + "\n"); // Console.WriteLine("New Packet Received From " + e.ToString() + " " + NewP.ToString()); if (OnMessageReceived != null) { OnMessageReceived.Invoke(NewP); } // Continue Reading Packets UdpState s = new UdpState(); s.e = new IPEndPoint(Local_IP, Client_Port); s.u = UdpClient; UdpClient.BeginReceive(BeginReceive_UDP_Client_Callback, s); }
/// <summary> /// 停止监听 /// </summary> public void StopListen() { try { if (udpReceive != null) { udpReceive.Close(); } if (ipEndPoint != null) { ipEndPoint = null; } if (udpReceiveState != null) { udpReceiveState = null; } if (t != null && t.IsAlive) { t.Abort(); t = null; } } catch (Exception) { } }
/// <summary> /// Initiate listening for server pings and set a timeout /// </summary> private void StartListeningForServerPingBacks() { _readyHandler(false); // Listen on our IP addresses on our port var endPoint = new IPEndPoint(Helpers.GetCurrentIPAddress(), UdpClientPort); // Make sure we don't grab exclusive "rights" to our address so we can use the same port for send and receive. var udpClient = new UdpClient(); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.ExclusiveAddressUse = false; udpClient.Client.Bind(endPoint); // Setup our "state" object so the callback has access to the client and endpoint var state = new UdpState(endPoint, udpClient); // Setup our async receive // Our callback will be called if and when data comes in udpClient.BeginReceive(ReceiveServerPingCallback, state); // Setup a timeout timer. When the timer elapses we invoke the 'ready' callback and close our udpclient. var enableTimer = new Timer(2000); enableTimer.Elapsed += (e, o) => { _readyHandler(true); udpClient.Close(); }; enableTimer.AutoReset = false; enableTimer.Enabled = true; }
private void OnMessageReceived(IAsyncResult asrAsyncResult) { UdpState udsState = (UdpState)(asrAsyncResult.AsyncState); UdpClient udpClient = udsState.udpClient; IPEndPoint eptEndPoint = udsState.eptEndPoint; byte[] receiveBytes = udpClient.EndReceive(asrAsyncResult, ref eptEndPoint); string receiveString = Encoding.ASCII.GetString(receiveBytes); //indicate coms channel is open if (m_bDataChannelConnected == false) { m_bDataChannelConnected = true; //send message back confirming data channel is open SendDataViaDataChannel(c_strConnectionOpenMessage); //indicate that connection is open LocalDataChannelReady?.Invoke(); } if (receiveString != c_strConnectionOpenMessage) { DataFromDataChannelReady?.Invoke(receiveString); } //restart listening for messages udpClient.BeginReceive(new AsyncCallback(OnMessageReceived), udsState); Console.WriteLine($"Received: {receiveString}"); }
/// <summary> /// Publishes a Gelf message to the specified Graylog server. /// </summary> public void Publish(GelfMessage message) { var serializedGelfMessage = JsonConvert.SerializeObject(message, Formatting.Indented); byte[] bytes = serializedGelfMessage.GzipMessage(Constants.Encoding); if (Constants.MaxChunkSize < bytes.Length) { var chunkCount = (bytes.Length / Constants.MaxChunkSize) + 1; if (chunkCount > Constants.MaxChunkCount) { throw new GelfMessageTooBigException($"Message of size {bytes.Length} will break up into {chunkCount} chunks, which is greater than maximum of GELF standard {Constants.MaxChunkCount}"); } var messageId = ChunkedMessageHelper.GenerateMessageId(); var state = new UdpState { SendClient = client, Bytes = bytes, ChunkCount = chunkCount, MessageId = messageId, SendIndex = 0 }; var messageChunkFull = ChunkedMessageHelper.GetMessageChunkFull(state.Bytes, state.MessageId, state.SendIndex, state.ChunkCount); client.BeginSend(messageChunkFull, messageChunkFull.Length, SendCallback, state); } else { var state = new UdpState { SendClient = client, Bytes = bytes, ChunkCount = 0, MessageId = string.Empty, SendIndex = 0 }; client.BeginSend(bytes, bytes.Length, SendCallback, state); } }
public AsyncUdpClient(string ServerIP, int listenp, int remotep) { listenPort = listenp; remotePort = remotep; // 本机节点 localEP = new IPEndPoint(IPAddress.Any, listenPort); // 远程节点 remoteEP = new IPEndPoint(IPAddress.Parse(ServerIP), remotePort); // 实例化 udpReceive = new UdpClient(localEP); udpSend = new UdpClient(); // 分别实例化udpSendState、udpReceiveState udpSendState = new UdpState(); udpSendState.ipEndPoint = remoteEP; udpSendState.udpClient = udpSend; udpReceiveState = new UdpState(); udpReceiveState.ipEndPoint = remoteEP; udpReceiveState.udpClient = udpReceive; //receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //receiveSocket.Bind(localEP); //sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //sendSocket.Bind(remoteEP); }
private void SendDatagram(IPEndPoint remoteEP, UdpState udpState, string timeStamp, DatagramTypes datagramType, string text) { try { StringBuilder sendMessage = new StringBuilder(); sendMessage.AppendLine(); sendMessage.AppendLine(timeStamp); sendMessage.AppendLine(localClientVersion); sendMessage.AppendLine(Enum.GetName(typeof(DatagramTypes), datagramType)); sendMessage.AppendLine(localUserKey); sendMessage.AppendLine(localAddress.ToString()); sendMessage.AppendLine(localUserName); int headerLength = sendMessage.Length; sendMessage.Insert(0, headerLength); sendMessage.AppendLine(text); byte[] cipherMessage = Security.EncryptString(sendMessage.ToString()); sendUdpClient.BeginSend(cipherMessage, cipherMessage.Length, remoteEP, SendCallback, udpState); } catch (Exception ex) { ErrorHandler.ShowError(ex); } }
private void ReceiveCallback(IAsyncResult ar) { if (ar == _currentAsyncResult) { UdpClient c = (UdpClient)((UdpState)(ar.AsyncState)).c; IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; try { byte[] buffer = c.EndReceive(ar, ref e); UdpState s = new UdpState(e, c); _currentAsyncResult = _udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s); XPDataRefStream stream = XPDataRefStream.ReadFromArray(buffer); if (stream != null) { foreach (XPDataRefResult dataref in stream.DataRefs) { _dataRefs[dataref.dref_en - 1].Result = dataref; } DataRefUpdate(this, new XPDataRefEventArgs()); } } catch (Exception ex) { Console.WriteLine("XPlane not loaded?"); } } }
private bool SendMessages(IPEndPoint e, UdpClient u, byte[] message) { int waitCount = 0; UdpState s = new UdpState(); s.e = e; s.u = u; u.Connect(e); messageSent = false; u.BeginSend(message, message.Length, new AsyncCallback(SendCallback), s); while (!messageSent) { Thread.Sleep(100); if (waitCount++ > (message_SendTimeout / 100)) { UDP_Close(); throw new NetworkInterface_TimeoutException("Send message timeout"); } if (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested) { UDP_Close(); throw new NetworkInterface_AbortRequest("Abort requested"); } } // reset the timeout for the next message message_SendTimeout = DEFAULT_TIMEOUT; return(true); }
private void Initialization() { // IPAddress and PORT number portSend = 1; portReceive = 55056; IPAddr = "10.1.52.155"; // Timer for sending message keep-alive //timerKeepAlive(5); // IpEndPoint for receiving messages RemoteIpEndPointReceive = new IPEndPoint(IPAddress.Parse("10.1.52.155"), portReceive); // IpEndPoint for sending messages RemoteIpEndPointSend = new IPEndPoint(IPAddress.Parse(IPAddr), portSend); // UdpClient for receiving messages udpClientReceive = new UdpClient(); // UdpClient for sending messages udpClientSend = new UdpClient(); udpState = new UdpState(); // Calibration bytes from all 4 channels calibrationChannel1 = new byte[4]; calibrationChannel2 = new byte[4]; calibrationChannel3 = new byte[4]; calibrationChannel4 = new byte[4]; startReceiving = false; // Thread for receiving messages tReceive = new Thread(new ThreadStart(() => ReceiveMessages(udpClientSend))); tReceive.Start(); }
//Initialize communication public override void Initialize() { //Initialize UDP communications //Receive receive_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); receive_from_address = IPAddress.Parse("127.0.0.1"); receive_end_point = new IPEndPoint(receive_from_address, 20321); receiver = new UdpClient(receive_end_point); //receiver.Client.Bind(new IPEndPoint(receive_from_address,20321)); s = new UdpState(); s.e = receive_end_point; s.u = receiver; //register async callback for UDP communication receiver.BeginReceive(new AsyncCallback(ParseBCIdata), s); //Send //sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //send_to_address = IPAddress.Parse("192.168.0.6"); //Arduino ip //sending_end_point = new IPEndPoint(send_to_address, 8888); //Arduino port //send_to_address = IPAddress.Parse("10.252.31.166"); //Android ip (primary phone) base.Initialize(); }
protected void Start() { udpClient = new UdpClient(DEFAULT_PORT); IPEndPoint IPendPoint = new IPEndPoint(IPAddress.Any, DEFAULT_PORT); while (listen) { block.Reset(); UdpState udpState = new UdpState(); udpState.endPoint = IPendPoint; udpState.udpClient = udpClient; // Start an asynchronous socket to listen for connections. foreach (IPAddress hostName in Dns.GetHostEntry(Dns.GetHostName()).AddressList) { if (!hostName.ToString().Contains(":")) { Debug.Log("Waiting for a connection on " + hostName + " : " + DEFAULT_PORT + "..."); } } udpClient.BeginReceive(new AsyncCallback(OnConnect), udpState); block.WaitOne(); } }
private void endReceive(IAsyncResult asyncResult) { try { UdpState udpState = (UdpState)asyncResult.AsyncState; UdpClient udpClient = udpState.Client; IPEndPoint ipEndPoint = udpState.IPEndPoint; byte[] data = udpClient.EndReceive(asyncResult, ref ipEndPoint); if (data != null && data.Length > 0) { parseData(ipEndPoint, data); } if (acceptingConnections) { udpClient.BeginReceive(callback, udpState); } } catch (ObjectDisposedException) { // Suppress error #pragma warning disable 219 var a = 2; #pragma warning restore 219 } }
/// <summary> /// Starts listening for messages on the specified port /// </summary> public void Start() { IPAddress address = (this.localMessagesOnly ? IPAddress.Loopback : IPAddress.Any); IPEndPoint endpoint = new IPEndPoint(address, this.port); this.udp = new UdpClient(endpoint); AsyncCallback callback = new AsyncCallback(this.ProcessPacket); UdpState state = new UdpState(); state.Udp = udp; state.Endpoint = endpoint; state.Callback = callback; udp.BeginReceive(callback, state); }
///<summary> ///开始异步监听端口 ///</summary> public void Listening() { IPAddress ip = IPAddress.Any; try { if (this._ip != null) { if (!IPAddress.TryParse(this._ip, out ip)) { throw new ArgumentException("IP地址错误", "Ip"); } } _socket.Bind(new IPEndPoint(ip, this._port)); UdpState state = new UdpState(); state.Socket = _socket; state.Remote = new IPEndPoint(IPAddress.Any, 0); _socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state); IsListening = true; } catch (Exception ex) { IsListening = false; HandleException?.BeginInvoke(ex, null, null); } }
private void BeginReceivingMessages(int iListenPort) { // Receive a message and write it to the console. IPEndPoint eptEndPoint = new IPEndPoint(IPAddress.Any, iListenPort); try { Debug.Log($"Creating connection for address {eptEndPoint.ToString()}"); m_udpUdpListen = new UdpClient(eptEndPoint); } catch (Exception excException) { Debug.LogError($"Failed to setup message recieve connection for address {eptEndPoint.ToString()} due to {excException.Message}"); throw; } UdpState ustUdpState = new UdpState(); ustUdpState.eptEndPoint = eptEndPoint; ustUdpState.udpClient = m_udpUdpListen; Console.WriteLine("listening for messages"); m_udpUdpListen.BeginReceive(new AsyncCallback(OnMessageReceived), ustUdpState); m_bListeningForMessages = true; }
private void EndReceive(IAsyncResult ar) { try { UdpState s = ar.AsyncState as UdpState; if (s != null) { UdpClient udpClient = s.udpClient; IPEndPoint ip = s.ip; Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip); string msg = Encoding.UTF8.GetString(receiveBytes); string decryptMsg = AESHelper.Decrypt(msg); Console.WriteLine(decryptMsg); //处理接收过来的数据 handleMsg(decryptMsg, ip); udpClient.BeginReceive(EndReceive, s);//在这里重新开始一个异步接收,用于处理下一个网络请求 } } catch (Exception ex) { //处理异常 Console.WriteLine("server error" + ex.Message); } }
protected void PSMoveClientThreadedReadThreadStart() { IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); UdpState s = new UdpState(); while (_readerThreadExit == 0) { s.e = remoteEP; s.u = _udpClient; _reading = true; try { if (_udpClient != null) { _udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s); } } catch (System.Exception) { // socket closed exception Console.WriteLine("except from udp client begin receive"); } while (_reading) { if (_readerThreadExit == 1) { break; } Thread.Sleep(0); } } }
// function to start the listener // if the the listener is active, destroy it and restart // shall mark the flag that the listener is active private void StartListener() { // byte[] receiveBytes; // array of bytes where we shall store the data received isListening = false; //resolve the net card ip address var ipAddress = IPAddress.Parse(rcvCardIP); //get the ipEndPoint var ipLocalEndPoint = new IPEndPoint(ipAddress, portToListenTo); // if the udpclient interface is active destroy s.u?.Close(); //re initialise the udp client s = new UdpState { e = ipLocalEndPoint, u = new UdpClient(ipLocalEndPoint) }; // set to start listening isListening = true; // wait for data InitListenerCallBack(); }
protected override void Append(LoggingEvent loggingEvent) { try { byte[] bytes = this.RenderLoggingEvent(loggingEvent).GzipMessage(this.Encoding); if (MaxChunkSize < bytes.Length) { var chunkCount = (bytes.Length / MaxChunkSize) + 1; var messageId = GenerateMessageId(); var state = new UdpState() { SendClient = Client, Bytes = bytes, ChunkCount = chunkCount, MessageId = messageId, SendIndex = 0 }; var messageChunkFull = GetMessageChunkFull(state.Bytes, state.MessageId, state.SendIndex, state.ChunkCount); Client.BeginSend(messageChunkFull, messageChunkFull.Length, RemoteEndPoint, SendCallback, state); } else { var state = new UdpState() { SendClient = Client, Bytes = bytes, ChunkCount = 0, MessageId = null, SendIndex = 0 }; Client.BeginSend(bytes, bytes.Length, RemoteEndPoint, SendCallback, state); } } catch (Exception ex) { this.ErrorHandler.Error("Unable to send logging event to remote host " + this.RemoteAddress + " on port " + this.RemotePort + ".", ex, ErrorCode.WriteFailure); } }
private void OnPacketReceived(IAsyncResult ar) { UdpState state = (UdpState)ar.AsyncState; IPEndPoint endPoint = state.EndPoint; byte[] bytes = state.Client.EndReceive(ar, ref endPoint); // Create the packet. Packet packet = new Packet(bytes); // Notify any listeners. EventHandler <PacketEventArgs> handler = PacketReceived; if (handler != null) { handler(this, new PacketEventArgs() { Packet = packet }); } // Read next packet. if (!_shutdownThread.WaitOne(0)) { state.Client.BeginReceive( new AsyncCallback(OnPacketReceived), state); } }
private Server() { udpClient = new UdpClient(RemoteIpEndPoint); UdpState s = new UdpState(udpClient, RemoteIpEndPoint); udpClient.BeginReceive(EndReceive, s); }
protected void PSMoveClienDelegateReadThread() { IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); UdpState s = new UdpState(); while (_readerThreadExit == 0) { s.e = remoteEP; s.u = _udpClient; _reading = true; try { if (_udpClient != null) _udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s); } catch (System.Exception) { // socket closed exception Console.WriteLine("except from udp client begin receive"); } while (_reading) { if (_readerThreadExit == 1) { break; } Thread.Sleep(0); } } }
public static void ReceiveCallback(IAsyncResult ar) { UdpState s = ((UdpState)(ar.AsyncState)); AllUDPStates.Add(s); byte[] receiveBytes = { }; try { receiveBytes = s.u.EndReceive(ar, ref s.ep); } catch { // Re-Listening while (true) { try { s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s); break; } catch { //Console.WriteLine("Unable to re-listen. Retrying..."); } } return; } string receiveString = Encoding.ASCII.GetString(receiveBytes); // Receiving any messages while (true) { try { s.u.BeginReceive(new AsyncCallback(ReceiveCallback), s); break; } catch { } } Console.WriteLine($"Received: {receiveString}"); // Broadcasting image if (receiveString == "Send me stuff!") { byte[] datagram = Encoding.ASCII.GetBytes("Okay here you go!"); try { s.u.Send(datagram, datagram.Length, s.ep); } catch { Console.WriteLine("Unable to send datagram to {0}!", s.ep.ToString()); return; } allThreads.Add(StartServingClientThread(s)); } }
private void ListenUdp() { var broadcastAddress = new IPEndPoint(_broadCastAddress, UdpServerPort); _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); _udpClient.ExclusiveAddressUse = false; _udpClient.Client.Bind(broadcastAddress); var udpState = new UdpState { EndPoint = broadcastAddress }; _udpClient.BeginReceive(ReceiveCallback, udpState); }
public Form1() { InitializeComponent(); IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, Properties.Settings.Default.portadr); UdpClient UdpClient = new UdpClient(RemoteIpEndPoint); UdpState UdpState = new UdpState(); UdpState.e = RemoteIpEndPoint; UdpState.u = UdpClient; UdpClient.BeginReceive(new AsyncCallback(receiveUDP), UdpState); }
void BeginRecieve() { // lock(client) { UdpState state = new UdpState(); state.endPoint = udpRemoteIpEndPoint; state.client = client; client.BeginReceive(new AsyncCallback(OnReceive), state); } }
private EmulatorServerController() { IPEndPoint e = new IPEndPoint(IPAddress.Any, udpPort); uClient = new UdpClient(udpPort); cDataController = EmulatorContactDataController.Instance; UdpState s = new UdpState(); s.e = e; s.u = uClient; uClient.BeginReceive(new AsyncCallback(onRecevice), s); }
void RecieveCandidates() { IPEndPoint remote_end = new IPEndPoint (IPAddress.Any, startup_port); UdpClient udp_client = new UdpClient (remote_end); udp_client.JoinMulticastGroup (group_address); UdpState s = new UdpState(); s.e = remote_end; s.u = udp_client; // async callback for multicast udp_client.BeginReceive (new AsyncCallback (ServerLookup), s); }
public Network_listener() { sock = new UdpClient(); sock.ExclusiveAddressUse = false; sock.EnableBroadcast = true; sock.Client.Bind(ep_server); UdpState s = new UdpState(); s.e = ep_server; s.u = sock; sock.BeginReceive(new AsyncCallback(this.ReceiveCallback), s); }
public AsyncUdpSever() { ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort); remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort); udpReceive = new UdpClient(ipEndPoint); udpSend = new UdpClient(); udpReceiveState = new UdpState(); udpReceiveState.udpClient = udpReceive; udpReceiveState.ipEndPoint = ipEndPoint; udpSendState = new UdpState(); udpSendState.udpClient = udpSend; udpSendState.ipEndPoint = remoteEP; }
/// <summary> /// Initializes the listner for bulb messages /// </summary> public void Initialize() { IPEndPoint end = new IPEndPoint(IPAddress.Any, 56700); mListnerClient = new UdpClient(end); mListnerClient.Client.Blocking = false; UdpState udpState = new UdpState(); udpState.endPoint = end; udpState.udpClient = mListnerClient; mListnerClient.Client.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); mListnerClient.BeginReceive(new AsyncCallback(ReceiveCallback), udpState); mIsInitialized = true; }
IEnumerator receive_loop() { var e = new System.Net.IPEndPoint(System.Net.IPAddress.Any, listenPort); var u = new System.Net.Sockets.UdpClient(e); u.EnableBroadcast = true; var s = new UdpState(); s.e = e; s.u = u; for (;;) { received = false; u.BeginReceive(new System.AsyncCallback(ReceiveCallback), s); while (!received) { yield return null; } } }
public static void receiveCallback(IAsyncResult ar) { UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u; IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; Byte[] receiveBytes = u.EndReceive(ar, ref e); string receiveString = Encoding.ASCII.GetString(receiveBytes); System.Reflection.MethodBase oMethod = System.Reflection.MethodBase.GetCurrentMethod(); CommonLib.CLogHandler.LogTrace(oMethod, receiveString); UdpState s = new UdpState(); s.e = e; s.u = u; u.BeginReceive(new AsyncCallback(receiveCallback), s); }
public static void receiveMessages() { // Receive a message and write it to the console. IPEndPoint e = new System.Net.IPEndPoint( System.Net.IPAddress.Parse(CDLLReadSetting.ReadSetting("//configuration/appSettings/add[@key='UDPServerIPAddress']")), Convert.ToInt32(CDLLReadSetting.ReadSetting("//configuration/appSettings/add[@key='UDPServerPort']"))); UdpClient u = new UdpClient(e); UdpState s = new UdpState(); s.e = e; s.u = u; u.BeginReceive(new AsyncCallback(receiveCallback), s); while (true) { } }
public MulticastClient(string multicastIP, int port) { client = new UdpClient(); IPEndPoint localEp = new IPEndPoint(IPAddress.Any, port); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.ExclusiveAddressUse = false; client.Client.Bind(localEp); IPAddress multicastaddress = IPAddress.Parse(multicastIP); client.JoinMulticastGroup(multicastaddress); state = new UdpState(); state.e = localEp; state.c = client; }
public AsyncUdpSever(string ServerIP) { // 本机节点 ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort); // 远程节点 remoteEP = new IPEndPoint(IPAddress.Parse(ServerIP), remotePort); // 实例化 udpReceive = new UdpClient(ipEndPoint); udpSend = new UdpClient(); // 分别实例化udpSendState、udpReceiveState udpReceiveState = new UdpState(); udpReceiveState.udpClient = udpReceive; udpReceiveState.ipEndPoint = ipEndPoint; udpSendState = new UdpState(); udpSendState.udpClient = udpSend; udpSendState.ipEndPoint = remoteEP; }
public void receiveUDP(IAsyncResult ar) { //UDP State Setup UdpState UpdState = new UdpState(); UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u; IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; //Receive Buffer Array Byte[] receiveBytes = u.EndReceive(ar, ref e); string receiveString = Encoding.ASCII.GetString(receiveBytes); //char[] delimiterChar = { ' ' }; //string[] strValues = receiveString.Split(delimiterChar); Invoke(new MethodInvoker(delegate { logging.displayERROR(false, false, true, receiveString, Color.Red); dataSTREAM.SelectionStart = dataSTREAM.Text.Length; dataSTREAM.ScrollToCaret(); })); //Invoke(new MethodInvoker(delegate { dataSTREAM.AppendText(receiveString); dataSTREAM.SelectionStart = dataSTREAM.Text.Length; dataSTREAM.ScrollToCaret(); })); UpdState.u = u; UpdState.e = e; u.BeginReceive(new AsyncCallback(receiveUDP), UpdState); }
public void listen() { _listen = true; IPEndPoint e = new IPEndPoint (IPAddress.Any, _listenPort); UdpClient u = new UdpClient (e); UdpState s = new UdpState (); s.e = e; s.u = u; //Console.WriteLine ("listening for messages on port {0}", _listenPort); while (_listen) { if (u.Available > 0) u.BeginReceive (new AsyncCallback(ReceiveCallback), s); System.Threading.Thread.Sleep(100); } }
public Network_listener() { try { sock = new UdpClient(); sock.ExclusiveAddressUse = false; sock.EnableBroadcast = true; sock.Client.Bind(ep_server); UdpState s = new UdpState(); s.e = ep_server; s.u = sock; sock.BeginReceive(new AsyncCallback(this.ReceiveCallback), s); } catch (Exception) { Packet p = new Packet(); p.dataIdentifier = Packet.DataIdentifier.Debug; p.message = "Listener ERROR. Disabling..."; Network_Broadcast.send(p); } }
private void buttonConnect_Click(object sender, EventArgs e) { if (buttonConnect.Text == "Connect") { buttonConnect.Text = "Disconnect"; var ip = IPAddress.Parse(textBoxIpAddress.Text); var port = int.Parse(textBoxPort.Text); connection.Connect(ip, port); panel_Sending.Enabled = true; var s = new UdpState { Endpoint = new IPEndPoint(ip, port), Client = connection }; connection.BeginReceive(MessageReceived, s); } else { buttonConnect.Text = "Connect"; panel_Sending.Enabled = false; connection.Close(); } }
IEnumerator Listen() { UdpState s = new UdpState(client); do { s.Begin(); while(listen && s.Data == null) { yield return 1; // check again at next frame } if (!listen) break; object[] msg = Osc.ToArray(s.Data); foreach(GameObject listener in listeners) { listener.BroadcastMessage("OnOscMessage", msg); if (debug) { string ds = ""; foreach(object o in msg) ds += o.ToString() + " "; Debug.Log(ds); } } } while(listen); }
/// <summary> /// Starts listening for messages on the specified port /// </summary> public void Start() { IPAddress address = (this.localMessagesOnly ? IPAddress.Loopback : IPAddress.Any); IPEndPoint endpoint = new IPEndPoint(address, this.port); this.udp = new UdpClient(endpoint); AsyncCallback callback = new AsyncCallback(this.ProcessPacket); UdpState state = new UdpState(); state.Udp = udp; state.Endpoint = endpoint; state.Callback = callback; udp.BeginReceive(callback, state); }
public static void ServerStart(object Parameter) { lock (locker) { Debug.Print(System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + "--" + Thread.CurrentThread.Name); //--------- ReciveEnabled = true; /* Socket client = null; IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); IPEndPoint localEndPoint = new IPEndPoint(localIPs[2], Convert.ToInt32 (Parameter)); Socket listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp ); listenSocket.Bind(localEndPoint); listenSocket.Listen(2); client = listenSocket.Accept(); Debug.WriteLine("Kliens bejelentkezett, a következő IP címről: {0}", ((IPEndPoint)client.RemoteEndPoint).Address.ToString()); byte[] data = new byte[256]; int length = client.Receive(data); Debug.WriteLine("A kliens üzenete: {0}",Encoding.ASCII.GetString(data, 0, length));*/ /* //Creates a UdpClient for reading incoming data. UdpClient receivingUdpClient = new UdpClient(11000); //Creates an IPEndPoint to record the IP Address and port number of the sender. // The IPEndPoint will allow you to read datagrams sent from any source. IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); try { reciveData data =new reciveData(); // Blocks until a message returns on this socket from a remote host. Byte[] receiveData = receivingUdpClient.Receive(ref RemoteIpEndPoint); Debug.WriteLine(reciveData. string returnData = Encoding.ASCII.GetString(receiveData); Debug.WriteLine("This is the message you received " + returnData.ToString()); Debug.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString()); } catch (Exception e) { Debug.WriteLine(e.ToString()); } */ Debug.WriteLine(Convert.ToString(Thread.CurrentThread.ManagedThreadId), "Szál-Id: {0}"); int listenPort = Convert.ToInt32(Parameter); try { IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, listenPort); UdpClient client = new UdpClient(endpoint); UdpState oState = new UdpState(); oState.ep = endpoint; oState.cl = client; while (ReciveEnabled) { Debug.WriteLine("listening for messages"); done.Reset(); client.BeginReceive(new AsyncCallback(ReceiveCallback), oState); // Do some work while we wait for a message. For this example, // we'll just sleep done.WaitOne(); } //client.EndReceive( IAsyncResult ar, ref endpoint); //ReceiveCallback(null); client.Client.Shutdown(SocketShutdown.Both); client.Client.Close(); client.Close(); client = null; } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message.ToString()); } } }
public bool Start(int udpPort) { if (socket == null) socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { if (logVerbose) Log.Info("UDPHelper: Starting listener on port {0}", udpPort); // Port already used? IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] connections = properties.GetActiveTcpConnections(); foreach (TcpConnectionInformation c in connections) if (c.RemoteEndPoint.Port == udpPort) { Log.Info("UDPHelper: UDP port {0} is already in use", udpPort); return false; } IPAddress hostIP = IPAddress.Parse("127.0.0.1"); IPEndPoint endPoint = new IPEndPoint(hostIP, udpPort); udpClient = new UdpClient(endPoint); UdpState state = new UdpState(); state.EndPoint = endPoint; state.UdpClient = udpClient; udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), state); if (logVerbose) Log.Info("UDPHelper: Listening for messages on port {0}", udpPort); return true; } catch (SocketException se) { Log.Info("UDPHelper: Start port {0}: {1} - {2}", udpPort, se.ErrorCode, se.Message); return false; } }
private void ListenOnUDP() { LogDelegate log = new LogDelegate(this.Bench.Log); // UDP sample from http://stackoverflow.com/questions/8274247/udp-listener-respond-to-client UdpClient listener; IPEndPoint groupEP; listener = new UdpClient(listenPort); groupEP = new IPEndPoint(IPAddress.Any, listenPort); try { if (messageReceived == false) { UdpState s = new UdpState(); s.e = groupEP; s.u = listener; log("Waiting for broadcast"); listener.BeginReceive(new AsyncCallback(ReceiveCallback), s); //byte[] bytes = listener.Receive(ref groupEP); } } catch (Exception e) { UDPResponse = ""; log(e.ToString()); } finally { if (messageReceived == true) { listener.Close(); messageReceived = false; } } }
/// <summary> /// Intizializes the <see cref="ILogProvider"/>. /// </summary> /// <param name="logHandler">The <see cref="ILogHandler"/> that may handle incomming <see cref="LogMessage"/>s.</param> public override void Initialize(ILogHandler logHandler) { base.Initialize(logHandler); try { mUdpClient = new UdpClient(); mUdpClient.Client = new Socket( AddressFamily.InterNetwork , SocketType.Dgram , ProtocolType.Udp); IPEndPoint localEP = new IPEndPoint( mListenInterface.Address , mListenInterface.Port); mUdpClient.Client.Bind(localEP); if (mMulticastIpAddress != null) { try { mUdpClient.JoinMulticastGroup( mMulticastIpAddress , mListenInterface.Address); } catch (Exception ex) { Logger.Warn(ex.Message); } } UdpState state = new UdpState( mUdpClient , mListenInterface); mUdpClient.BeginReceive( ReceiveUdpMessage , state); } catch (Exception ex) { Logger.Warn(ex.Message); } }
/********************/ /****** CLIENT ******/ /********************/ public void ListenServer() { // open a listening port on a random port // to receive a response back from server // using 0 doesn't seem to work reliably // so we'll just do it ourselves int myPort = UnityEngine.Random.Range(15001,16000); IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, myPort); UdpClient uc1 = new UdpClient(ep1); UdpState us1 = new UdpState(); us1.e = ep1; us1.u = uc1; uc1.BeginReceive(new AsyncCallback(ListenServerCallback), us1); broadcastClient = uc1; broadcastEndPoint = ep1; Debug.Log("Broadcast listener opened on port " + broadcastEndPoint.Port.ToString()); }
/********************/ /****** SERVER ******/ /********************/ public void ListenForClients(string g) { // open a listening port on known port 15000 // to listen for any clients IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, 15000); UdpClient uc1 = new UdpClient(ep1); UdpState us1 = new UdpState(); us1.e = ep1; us1.u = uc1; uc1.BeginReceive(new AsyncCallback(ListenForClientsCallback), us1); multiGameName = g; waitingResponse = true; Debug.Log("Server listening port opened"); }
private void ServerThread() { UdpClient udpClient = new UdpClient(8123); while (_run) { IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); UdpState s = new UdpState { E = remoteIpEndPoint, U = udpClient }; udpClient.BeginReceive(ServerReceiveCallback, s); while (!_messageReceived) { Thread.Sleep(10); } _messageReceived = false; } }
// Connect to the time server with timeout and update system time if specified public bool Connect(int Timeout, bool UpdateSystemTime) { try { // Resolve server address IPHostEntry hostEntry = Dns.GetHostEntry(TimeServer); IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 123); // Create a UDP client to connect to the time server UdpClient udpClient = new UdpClient(); // Save state information for the UDP receive callback UdpState udpState = new UdpState(endPoint, udpClient, ref NTPData); // Connect to the time server udpClient.Connect(endPoint); // Initialize NTP data structure and send request NTPDataInit(); udpClient.Send(NTPData, NTPData.Length); // Wait for response with timeout IAsyncResult asyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), udpState); for (int i = Timeout * 10; i > 0 && !asyncResult.IsCompleted; i--) { Thread.Sleep(100); } if (!asyncResult.IsCompleted) { // No response from time server //udpClient.EndReceive(asyncResult, ref endPoint); return false; } Thread.Sleep(100); if (!IsResponseValid()) { throw new Exception("Invalid response from " + TimeServer); } ReceptionTimestamp = DateTime.Now; } catch (SocketException e) { throw new Exception(e.Message); } // Update system time if (UpdateSystemTime) { SetTime(); } return true; }