public ServerPlayers GetServerChallengeSync(GetServerInfoSettings settings) { var localEndpoint = new IPEndPoint(IPAddress.Any, 0); using (var client = new UdpClient(localEndpoint)) { client.Client.ReceiveTimeout = settings.ReceiveTimeout; client.Client.SendTimeout = settings.SendTimeout; client.Connect(EndPoint); var requestPacket = new List<byte>(); requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 }); requestPacket.AddRange(BitConverter.GetBytes(-1)); client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length); byte[] responseData = client.Receive(ref localEndpoint); requestPacket.Clear(); requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 }); requestPacket.AddRange(responseData.Skip(5).Take(4)); client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length); responseData = client.Receive(ref localEndpoint); return ServerPlayers.Parse(responseData); } }
static void Main(string[] args) { byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 19511); UdpClient newsock = new UdpClient(ipep); Console.WriteLine("Waiting for a client..."); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); data = newsock.Receive(ref sender); Console.WriteLine("Message received from {0}:", sender.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); newsock.Send(data, data.Length, sender); while (true) { data = newsock.Receive(ref sender); Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); newsock.Send(data, data.Length, sender); } }
public Reciver(string portString,HlavneOkno ho) { this.ho = ho; int port = 0; if (Int32.TryParse(portString, out port)==false) { return; } socket = new UdpClient(port); IPEndPoint server = new IPEndPoint(IPAddress.Any, port); System.Threading.ThreadPool.QueueUserWorkItem(delegate { try { byte[] packet = socket.Receive(ref server); ocakavany = Int32.Parse(Encoding.ASCII.GetString(packet).Substring(4, 4)); pocet++; } catch (Exception ex) { Console.WriteLine(ex.Message); } sprava = new String[ocakavany]; Thread.Sleep(20); while (nacitavaj) { try { byte[] packet = socket.Receive(ref server); String Sprava = Encoding.ASCII.GetString(packet).Substring(4,packet.Length-4); Int32 poradie = Int32.Parse(Encoding.ASCII.GetString(packet).Substring(0,4)); sprava[poradie] = Sprava; pocet++; } catch (Exception ex) { Console.WriteLine(ex.Message); } Thread.Sleep(20); if (pocet == ocakavany) { ho.pocuvatStop_Click(); break; } } }, null); }
private static void ReceiveMessage() { System.Net.Sockets.UdpClient receiver = new System.Net.Sockets.UdpClient(LOCAL_PORT); // UdpClient for receiving incoming data // IPEndPoint remoteIp = new IPEndPoint(IPAddress.Parse("80.234.45.88"), 8888); // address of the sending server IPEndPoint remoteIp = null; // address of the sending server (NULL means Any) try { while (true) { byte[] data = receiver.Receive(ref remoteIp); // receive data from the server // string message = Encoding.Unicode.GetString(data); //Console.WriteLine("server data: {0}", message); Console.WriteLine($"Received broadcast from {remoteIp}"); Console.WriteLine($" {Encoding.ASCII.GetString(data, 0, data.Length)}"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { receiver.Close(); } }
private void UdpReceiveProc() { while (!m_ShuttingDown) { NET.IPEndPoint remoteEp = null; byte[] data = null; try { data = m_udpClient.Receive(ref remoteEp); } catch (Exception) { } if (null != data) { string sipMsg = g_Ascii.GetString(data, 0, data.Length); m_Settings.WriteMessageToLog( LogMessageType.Information + 3, string.Format( CultureInfo.CurrentUICulture, "SIP message received from {0}:{1}\n{2}", remoteEp.Address, remoteEp.Port, sipMsg ) ); base.OnSipReceivedFromClient( new SipMessageEventArgs(sipMsg, remoteEp) ); } } }
protected override void Loop(CancellationToken token) { using (var udpClient = new UdpClient(NavdataPort)) { udpClient.Connect(_configuration.DroneHostname, NavdataPort); SendKeepAliveSignal(udpClient); var droneEp = new IPEndPoint(IPAddress.Any, NavdataPort); Stopwatch swKeepAlive = Stopwatch.StartNew(); Stopwatch swNavdataTimeout = Stopwatch.StartNew(); while (token.IsCancellationRequested == false && swNavdataTimeout.ElapsedMilliseconds < NavdataTimeout) { if (udpClient.Available > 0) { byte[] data = udpClient.Receive(ref droneEp); var packet = new NavigationPacket { Timestamp = DateTime.UtcNow.Ticks, Data = data }; _navigationPacketAcquired(packet); swNavdataTimeout.Restart(); } if (swKeepAlive.ElapsedMilliseconds > KeepAliveTimeout) { SendKeepAliveSignal(udpClient); swKeepAlive.Restart(); } Thread.Sleep(5); } } }
private void listen() { UdpClient uc = new UdpClient(9527);//udp协议添加端口号 while (true) { IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0);//将网络端点转化为ip地址 和端口号 byte[] bmsg = uc.Receive(ref ipep);//返回有远程主机发出的udp数据报 string msg = Encoding.Default.GetString(bmsg);//将字节转化为文本 string[] s = msg.Split('|');//元素分隔 if(s.Length != 4) { continue; } if(s[0]=="LOGIN") { Friend friend=new Friend(); int curIndex = Convert.ToInt32(s[2]); if (curIndex<0 || curIndex>=this.ilHeadImages.Images.Count) { curIndex = 0; } friend.HeadImageIndex =curIndex; friend.NickName = s[1]; friend.Shuoshuo=s[3]; object[] pars=new object[1]; pars[0]=friend; this.Invoke(new delAddFriend(this.addUcf),pars[0]); } } }
void sendPos() { bufin = SerializeNetchan(1, 2); Netchan net = deserializeNetchan(bufin); print("Sending...\nProtocol: " + net.Protocol + "\nSequence: " + net.Sequence + "\nAck: " + net.Ack); client.Send(bufin, bufin.Length); bufout = client.Receive(ref ep); net = deserializeNetchan(bufout); Player p = net.Players(0).Value; print("Receiving...\nProtocol: " + net.Protocol + "\nSequence: " + net.Sequence + "\nAck: " + net.Ack + "\n x: " + p.Rot.Value.X + "\n y: " + p.Rot.Value.Y + "\n z: " + p.Rot.Value.Z); print(net.ByteBuffer.Data); var i = 0; foreach (Transform t in networkedPlayers) { i++; t.position = new Vector3(p.Pos.Value.X, p.Pos.Value.Y, (float)p.Pos.Value.Z + 2 * i); t.eulerAngles = new Vector3(p.Rot.Value.X, p.Rot.Value.Y, p.Rot.Value.Z); //t.rotation = new Quaternion(p.Rot.Value.X, p.Rot.Value.Y, p.Rot.Value.Z, 0); } }
private void UdpListen() { while (true) { try { var bytes = _udpServer.Receive(ref _groupAddresses); if (!Equals(Encoding.UTF8.GetString(bytes), _broadcastMessage)) { continue; } var sendBuff = Encoding.UTF8.GetBytes(_tcpPort.ToString()); _udpServer.Send(sendBuff, sendBuff.Length, _groupAddresses.Address.ToString(), _groupAddresses.Port); } catch (ObjectDisposedException) { return; } catch (SocketException) { return; } catch (InvalidOperationException) { return; } } }
protected void serverLoop() { Trace.WriteLine("Waiting for UDP messages."); listener = new UdpClient(UDP_PORT); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDP_PORT); byte[] receive_byte_array; bool running = true; while (running) { try { receive_byte_array = listener.Receive(ref groupEP); if (receive_byte_array.Length != 2) { Trace.WriteLine("Invalid UDP message received. Ignored message!"); continue; } Trace.WriteLine("Upp fan speed message received."); int fan = receive_byte_array[0]; byte speed = receive_byte_array[1]; fanControlDataObject.setPinSpeed(fan, speed, true); } catch { running = false; } } }
public void Listen() { using (var udpClient = new UdpClient(_listenPort)) { _listen = true; var remoteEp = new IPEndPoint(IPAddress.Any, _listenPort); while (_listen) { var data = udpClient.Receive(ref remoteEp); if (data.Length <= 0) { continue; } if (_messageQueue.Count > _messageFloodLimit) //Overflow { continue; } var rawMessage = new RawMessage() { Port = remoteEp.Port, IpAddress = remoteEp.Address, Message = System.Text.Encoding.UTF8.GetString(data) }; _messageQueue.Enqueue(rawMessage); } udpClient.Close(); } }
private static void StartListener() { bool done = false; UdpClient listener = new UdpClient(listenPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); try { while (!done) { Thread.Sleep(100); Console.WriteLine("Waiting for broadcast"); byte[] bytes = listener.Receive(ref groupEP); Console.Write( Encoding.ASCII.GetString(bytes, 0, bytes.Length)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { listener.Close(); } }
public SensorState DoCheckState(Server target) { try { var udp_ep = new IPEndPoint(IPAddress.Any, 2280); UdpClient client = new UdpClient(udp_ep); client.Client.ReceiveTimeout = 3000; client.Send(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }, 4, target.FullyQualifiedHostName, Port); client.Receive(ref udp_ep); return SensorState.OK; } catch (SocketException) { return SensorState.Error; } catch (TimeoutException) { return SensorState.OK; } catch (Exception) { return SensorState.Error; } }
public void ThreadEcouteur() { //Déclaration du Socket d'écoute. UdpClient ecouteur = null; //Création sécurisée du Socket. try { ecouteur = new UdpClient(1800); } catch { MessageBox.Show("Impossible de se lier au port UDP 1800. Vérifiez vos configurations réseau."); return; } //Définition du Timeout. ecouteur.Client.ReceiveTimeout = 1000; //Bouclage infini d'écoute de port. while (_continuer) { try { IPEndPoint ip = null; byte[] data = ecouteur.Receive(ref ip); lstBoxMessage.Items.Add("Moi : " + richTxtBoxMessage.Text); } catch { } } ecouteur.Close(); }
/// <summary> /// Attempts to receive a packet. /// </summary> /// <param name="client">the UDP client to receive from</param> /// <returns>the length of the received packet or -1 if nothing was received</returns> /// public int Receive(UdpClient client) { source = new IPEndPoint(IPAddress.Any, 0); idx = 0; data = null; id = -1; length = 0; try { data = client.Receive(ref source); length = data.Length - 4; id = GetInt16(); int len = GetInt16(); if ( len != length ) { Debug.LogWarning("Packet length mismatch (" + length + " received, " + len + " announced)"); } errorCounter = 0; } catch (SocketException e) { if (errorCounter == 0) { Debug.LogWarning("Exception while waiting for MoCap server response (Time: " + Time.timeSinceLevelLoad + "s): " + e.Message); } errorCounter++; } return (data == null) ? -1 : length; }
/// <summary> /// Provides a one-time, preprocessing functionality for the cmdlet. /// </summary> protected override void BeginProcessing() { // Initialize parameters and base Incog cmdlet components this.InitializeComponent(); // Invoke Interative Mode if selected if (this.Interactive) this.InteractiveMode(); // Receiving messages endpoint IPEndPoint bobEndpoint = new IPEndPoint(this.LocalAddress, 53); // Sending messages endpoing IPEndPoint aliceEndpoint = new IPEndPoint(this.RemoteAddress, 0); // Open up the UDP port for packet capture UdpClient socket = new UdpClient(bobEndpoint); this.packetCapturing = true; do { byte[] payload = socket.Receive(ref aliceEndpoint); string text = System.Text.Encoding.ASCII.GetString(payload); this.ReceiveCovertMessage(text); } while (this.packetCapturing); socket.Close(); }
public void messageReceiver() { UdpClient activeListener = new UdpClient(receivingPort); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, receivingPort); string received_data; byte[] receive_byte_array; try { while (true) { receive_byte_array = activeListener.Receive(ref groupEP); received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length); string[] holster = received_data.Split(','); string username = holster[0]; string ip = holster[1]; userSemaphore.WaitOne(); usernames.Add(username); ips.Add(ip); userSemaphore.Release(); } } catch (Exception e) { } }
public List<string> get_available_IPs() { List<string> IPs_array = new List<string>(); // Создаем UdpClient для чтения входящих данных UdpClient receivingUdpClient = new UdpClient(UDP_port); IPEndPoint RemoteIpEndPoint = null; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); try { while (stopWatch.Elapsed.Seconds < 10) { // Ожидание дейтаграммы byte[] receiveBytes = receivingUdpClient.Receive( ref RemoteIpEndPoint); // Преобразуем и отображаем данные string returnData = Encoding.UTF8.GetString(receiveBytes); if (!IPs_array.Contains(returnData)) { IPs_array.Add(returnData); } } } catch (Exception ex) { MessageBox.Show("Ошибка: " + ex.Message, ex.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error ); return null; } return IPs_array; }
public static void Receiver() { // Создаем UdpClient для чтения входящих данных UdpClient receivingUdpClient = new UdpClient(localPort); IPEndPoint RemoteIpEndPoint = null; try { Console.WriteLine( "\n-----------*******Общий чат*******-----------"); while (true) { // Ожидание дейтаграммы byte[] receiveBytes = receivingUdpClient.Receive( ref RemoteIpEndPoint); // Преобразуем и отображаем данные Console.WriteLine(RemoteIpEndPoint.Address.ToString()); Console.WriteLine(RemoteIpEndPoint.Port.ToString()); string returnData = Encoding.UTF8.GetString(receiveBytes); Console.WriteLine(" --> " + returnData.ToString()); } } catch (Exception ex) { Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n " + ex.Message); } }
static void Main(string[] args) { String s; byte[] data; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 1165); UdpClient client = new UdpClient(ipep); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); String c; byte[] cdata; IPEndPoint cipep = new IPEndPoint(IPAddress.Any, 1166); UdpClient Cclient = new UdpClient(cipep); Cclient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); while (true) { data = client.Receive(ref ipep); s = Encoding.ASCII.GetString(data); Console.WriteLine(s.Substring(35,75));//only what we need to see //don't need the console stuff right now... //cdata = Cclient.Receive(ref cipep); //c = Encoding.ASCII.GetString(cdata); //Console.ReadLine(); //this will pause the console //Console.WriteLine(c); //we dont want to do this quite yet } }
public static void Listen(IPEndPoint remoteIP) { var done = false; var listener = new UdpClient(remoteIP); listener.Connect(remoteIP); var groupEP = new IPEndPoint(IPAddress.Any, remoteIP.Port); try { while (!done) { Console.WriteLine("Waiting for broadcast.."); byte[] bytes = listener.Receive(ref groupEP); string json = EncodingUtility.Decode(bytes); Console.WriteLine("Received broadcast from {0}:{1} :\n {2}\n", groupEP.Address,groupEP.Port, json); var message = JsonHelper.JsonDeserialize<ExchangeAMd>(json); //Do aaync ProcessOrder(message); } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { listener.Close(); } }
public static void StartListener(int port) { UdpClient client = new UdpClient(); client.ExclusiveAddressUse = false; 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("239.0.0.222"); //client.JoinMulticastGroup(multicastaddress); while (true) { Byte[] data = client.Receive(ref localEp); string strData = Encoding.ASCII.GetString(data); eventH e = JsonConvert.DeserializeObject<eventH>(strData); e.handle(); } }
private void UdpReceiveProc() { while (!m_bShuttingDown) { NET.IPEndPoint remoteEp = null; byte[] data = null; try { data = m_udpClient.Receive(ref remoteEp); } catch (Exception) { } if (null != data) { byte[] newData = new byte[1 + m_BranchAscii.Length + data.Length]; newData[0] = (byte)m_BranchAscii.Length; m_BranchAscii.CopyTo(newData, 1); data.CopyTo(newData, 1 + m_BranchAscii.Length); m_SipTransport.SendToPipe(newData); } } }
static void Main(string[] args) { // master branch IPEndPoint localpt = new IPEndPoint(IPAddress.Loopback, 6000); ThreadPool.QueueUserWorkItem(delegate { UdpClient udpServer = new UdpClient(); udpServer.ExclusiveAddressUse = false; udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpServer.Client.Bind(localpt); IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0); Console.WriteLine("Listening on " + localpt + "."); byte[] buffer = udpServer.Receive(ref inEndPoint); Console.WriteLine("Receive from " + inEndPoint + " " + Encoding.ASCII.GetString(buffer) + "."); }); // Sleep time was inreased. Thread.Sleep(10000); // git test 2 Console.ReadKey(); }
public static string Answer(string question) { if (SettingsManager.KAI) { if (Process.GetProcessesByName("KAIML").Length > 0) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15000); byte[] data = Encoding.ASCII.GetBytes(question); server.Send(data, data.Length, iep); server.Client.ReceiveTimeout = 4000; IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0); byte[] d = server.Receive(ref ipe); return(Encoding.UTF8.GetString(d)); } else { return("KAIML Process isn't runing"); } } else { return("Kavprot AIML Bot is disabled"); } }
private void BackgroundListener() { IPEndPoint bindingEndpoint = new IPEndPoint(IPAddress.Any, _endPoint.Port); using (UdpClient client = new UdpClient()) { client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.Bind(bindingEndpoint); client.JoinMulticastGroup(_endPoint.Address); bool keepRunning = true; while (keepRunning) { try { IPEndPoint remote = new IPEndPoint(IPAddress.Any, _endPoint.Port); byte[] buffer = client.Receive(ref remote); lock (this) { DataReceived(this, new MulticastDataReceivedEventArgs(remote, buffer)); } } catch (ThreadAbortException) { keepRunning = false; Thread.ResetAbort(); } } client.DropMulticastGroup(_endPoint.Address); } }
public (byte[], IPEndPoint) Receive() { IPEndPoint remote = null; var data = udp.Receive(ref remote); return(data, remote); }
public void Connect() { try { System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(this.TimeServer); System.Net.IPEndPoint endPoint = new System.Net.IPEndPoint(hostEntry.AddressList[0], 123); System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(); udpClient.Client.ReceiveTimeout = 3000; udpClient.Client.SendTimeout = 3000; udpClient.Connect(endPoint); this.Initialize(); udpClient.Send(this.NTPData, this.NTPData.Length); this.NTPData = udpClient.Receive(ref endPoint); this.ReceptionTimestamp = System.DateTime.Now; if (!this.IsResponseValid()) { throw new System.Exception("Invalid response from " + this.TimeServer); } } catch (System.Net.Sockets.SocketException ex) { Log.WriteError("NTPʱ¼ä»ñȡʧ°Ü£º" + ¡¡ex.Message); throw new System.Exception(ex.Message); } }
public static NameServerProxy locateNS(string host, int port) { if(host!=null) { if(port==0) port=Config.NS_PORT; NameServerProxy proxy=new NameServerProxy(host, port); proxy.ping(); return proxy; } if(port==0) port=Config.NS_BCPORT; IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Broadcast, port); using(UdpClient udpclient=new UdpClient()) { udpclient.Client.ReceiveTimeout = 2000; udpclient.EnableBroadcast=true; byte[] buf=Encoding.ASCII.GetBytes("GET_NSURI"); udpclient.Send(buf, buf.Length, ipendpoint); IPEndPoint source=null; try { buf=udpclient.Receive(ref source); } catch (SocketException) { // try localhost explicitly (if host wasn't localhost already) if(host==null || (!host.StartsWith("127.0") && host!="localhost")) return locateNS("localhost", Config.NS_PORT); else throw; } string location=Encoding.ASCII.GetString(buf); return new NameServerProxy(new PyroURI(location)); } }
/// <summary> /// Does the video job. /// </summary> private void DoWorkerJob(System.Net.Sockets.UdpClient socket, int data_port) { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, data_port); try { // loop until we get an exception eg the socket closed while (true) { byte[] frame = socket.Receive(ref ipEndPoint); // We have an RTP frame. // Fire the DataReceived event with 'frame' //Console.WriteLine("Received RTP data on port " + data_port); Rtsp.Messages.RtspChunk currentMessage = new Rtsp.Messages.RtspData(); // aMessage.SourcePort = ?? currentMessage.Data = frame; ((Rtsp.Messages.RtspData)currentMessage).Channel = data_port; OnDataReceived(new Rtsp.RtspChunkEventArgs(currentMessage)); } } catch (ObjectDisposedException) { } catch (SocketException) { } }
private string DiscoverServerAddress() { try { var client = new UdpClient(); var requestData = Encoding.ASCII.GetBytes("SomeRequestData"); var serverEp = new IPEndPoint(IPAddress.Any, 0); client.EnableBroadcast = true; client.Send(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 8888)); var serverResponseDataTask = Task<byte[]>.Factory.StartNew(() => client.Receive(ref serverEp)); var timeout = DateTime.Now.AddSeconds(10d); while (timeout > DateTime.Now && !serverResponseDataTask.IsCompleted) ; if (!serverResponseDataTask.IsCompleted) { return _serverAddress = "192.168.56.60:80"; } var serverResponse = Encoding.ASCII.GetString(serverResponseDataTask.Result); _serverAddress = $"{serverEp.Address.ToString()}:80"; } catch (Exception e) { Debug.WriteLine($"ServerFinder.DiscoverServerAddress: exception type: {e.GetType()}, msg: {e.Message}"); return _serverAddress = "192.168.56.60:80"; } Debug.WriteLine($"ServerFinder.DiscoverServerAddress: found server at {_serverAddress}"); return _serverAddress; }
private void listen() { UdpClient uc = new UdpClient(9527); while (true) { IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0); byte[] bmsg = uc.Receive(ref ipep); string scontent = Encoding.Default.GetString(bmsg); string[] data = scontent.Split('|'); if(data[0]=="INROOM") { this.txt_person.Text += data[1] + "上线了\r\n"; } if(data[0]=="PUBLIC") { int l = data.Count(); if(l>3) { this.txtHistory.Text += data[2] + ":\r\n"; this.txtHistory.Text += data[2] + "\r\n"; } } } }
private void HardwareReadout() { try { //Creates a UdpClient for reading incoming data. UdpClient receivingUdpClient = new UdpClient(_poort); //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); while (true) { byte[] receivedData = receivingUdpClient.Receive(ref RemoteIpEndPoint); // Blocking untill new data if (NewData != null) { // Synchroon NewData(receivedData); // Asynchroon //Task.Factory.StartNew(() => NewData(receivedData)); } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Receiver error"); } }
void ReceiveMessage() { while (isRuning) { try { if (udpClient.Available < 1) { continue; } if (udpClient == null) { return; } byte[] bytRecv = udpClient.Receive(ref remoteIpep); string message = encoding.GetString(bytRecv, 0, bytRecv.Length); if (NewReceive != null) { NewReceive(remoteIpep, message); } } catch (SocketException ex) { if (OnError != null) { OnError(ex.Message); } } } }
private void listen() { UdpClient uc = new UdpClient(9527); while (true) { IPEndPoint ipep = new IPEndPoint(IPAddress.Any,0); byte[] bmsg = uc.Receive(ref ipep); string msg = Encoding.Default.GetString(bmsg); string[] s = msg.Split('|'); if (s[0] == "PUBLIC") { this.txtHistory.Text += s[2] +":"+ "\r\n"; this.txtHistory.Text += s[1] + "\r\n"; } else if (s[0] == "INROOM") { this.txtHistory.Text += s[1] + "登录了" + "\r\n"; } else { return; } } }
static void Main(string[] args) { Console.WriteLine("Input Desired Port:"); string input = Console.ReadLine(); short port = Int16.Parse(input.Split(' ')[0]); IPEndPoint cont = null; IPEndPoint copter = new IPEndPoint(IPAddress.Parse("192.168.1.1"), port); UdpClient cli = new UdpClient(port); IPEndPoint remoteHost = null; while (true) { byte[] recieved = cli.Receive(ref remoteHost); if (remoteHost.Equals(copter)) { Console.WriteLine("Packet recieved from copter at ({0})", remoteHost); if (cont != null) { Console.WriteLine("Sending to ({0})", cont); cli.Send(recieved, recieved.Length, cont); } } else { cont = remoteHost; Console.WriteLine("Packet recieved from controller at ({0})", remoteHost); Console.WriteLine("Sending to ({0})", copter); cli.Send(recieved, recieved.Length, copter); } } }
void UdpEchoClientMethod(string[] args) { //Check for correct amount of arguments. if ((args.Length < 2) || (args.Length > 3)) throw new ArgumentException("Parameters: <Server> <Word> [<Port>]"); //Name/IPAddress string server = args[0]; //Use port argument if supplied, otherwise default to 7 int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7; //Convert input string to an array of bytes. byte[] sendPacket = Encoding.ASCII.GetBytes(args[1]); //Create a UdpClient instance UdpClient client = new UdpClient(); try { //Send the echo string(packet) to the specified host and port client.Send(sendPacket, sendPacket.Length, server, servPort); Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length); //This IPEndPoint instance will be populated with the remote sender's endpoint information after the Receive() call IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0); //Attempt echo reply receive byte[] rcvPacket = client.Receive(ref remoteIPEndPoint); Console.WriteLine("Received {0} bytes from {1}: {2}", rcvPacket.Length, remoteIPEndPoint, Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length)); } catch (SocketException se) { Console.WriteLine(se.ErrorCode + ": " + se.Message); } client.Close(); }
public void SendBytesNow_LoopBack_SequenceNumber16K() { int i; bool result = false; UDPSender us = new UDPSender("127.0.0.1", 7770); byte[] data = new byte[1024 * 16]; for (i = 0; i < data.Length; i++) { data[i] = (byte)i; } UdpClient listener = new UdpClient(7770); IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 7770); //Blocking Call us.SendBytesNow(data, 1024 * 16); //BLOCKING CALL byte[] bytes = listener.Receive(ref groupEP); for (i = 0; i < data.Length; i++) { if (bytes[i] != (byte)i) { Assert.True(false); } } Assert.True(true); listener.Close(); }
static void Main(string[] args) { UdpClient udp = new UdpClient(8005); IPAddress ipAddr = GetIPAddress(args[0]); int port = GetPort(args[1]); IPEndPoint remoteEP = new IPEndPoint(ipAddr, port); ASCIIEncoding ascii = new ASCIIEncoding(); byte[] rgbDataGram = ascii.GetBytes("Hello World"); string returnData = null; while (ipAddr != null && port != 0) { returnData = Encoding.ASCII.GetString(rgbDataGram); Console.Write("Sending string: "); Console.WriteLine(returnData); // send it udp.Send(rgbDataGram, rgbDataGram.Length, remoteEP); // wait for a byte to come in. rgbDataGram = udp.Receive(ref remoteEP); returnData = Encoding.ASCII.GetString(rgbDataGram); Console.Write("Received string: "); Console.WriteLine(returnData); // 5 sec wait Thread.Sleep(5000); } }
public void ReceiveStuff(CancellationToken cancelationToken) { while (!cancelationToken.IsCancellationRequested) { IPEndPoint remoteEp = new IPEndPoint(IPAddress.Any, 1500); byte[] bytes = null; try { bytes = _myUdpClient.Receive(ref remoteEp); } catch (SocketException err) { if (err.SocketErrorCode != SocketError.TimedOut) { throw; } } if (bytes != null) { ReceivedData(bytes); } } }
public void ReceiveAnswer() { IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receivedBytes = _udpClient.Receive(ref remoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receivedBytes); Console.WriteLine(returnData); }
private void ThreadFunction_Recv() { try { while (_thread_running && isConnected) { var bufraw = _inner_socket.Receive(ref _server_endpoint); if (bufraw.Length > 4) { byte[] buf = Base.MemoryPool.Alloc(bufraw.Length - 4); //new byte[bufraw.Length - 4]; Array.Copy(bufraw, 4, buf, 0, bufraw.Length - 4); XOREncrypt.Decrypt(buf, bufraw.Length - 4); MsgStream msg = MsgStream.Create(buf, bufraw.Length - 4); if (msg.IsCustomCmd) { if (msg.CustomType == CustomMsgType.ping) { //服务器返回了 证明连接成功了 _IsConnected = true; TimeSpan ts = DateTime.Now - mLastPingTime;//mLastPingTimes[idx]; mPing = (int)(ts.TotalMilliseconds); mLastPingTime = DateTime.Now; // this.LastSendPingTimestamp = Utils.GetTimestampSecondsInt(); msg.Dispose(); continue; } } //服务器返回了 证明连接成功了 _IsConnected = true; _recvQueue.Enqueue(msg); } else { //<=4 } } } catch (SocketException e) { Debug.Log("UdpSocket:" + e.Message + " " + e.ErrorCode + " " + e.NativeErrorCode + " " + e.SocketErrorCode); } catch (Exception e) { Debug.Log("UdpSocket:" + e.Message); } this.Disconnected(); while (_recvQueue.Empty() == false) { var x = _recvQueue.Dequeue(); if (x != null) { x.Dispose(); } } Debug.Log("[NetWork]:UdpSocket Recv Thread Close"); }
public string REG_RD(out UInt32 DATA, Int16 ADDRESS, bool IMP) { byte[] packet = { 0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff }; packet[4] = (byte)((ADDRESS >> 8) & 0xff); packet[5] = (byte)(ADDRESS & 0xff); packet[9] = 0x00; try { RDREG_UDP.Send(packet, 12, RDREG_EP); packet = RDBKREG_UDP.Receive(ref RDBKREG_EP); DATA = ((UInt32)packet[2] << 24) | ((UInt32)packet[3] << 16) | ((UInt32)packet[4] << 8) | (UInt32)packet[5]; return("ok V3"); } catch (Exception e) { DATA = 0; return("read failed" + e.ToString()); } }
private void SendReceiveMsg() { try { remoteCLIPE = new IPEndPoint(IPAddress.Any, 0); while (_IsStarted) { //if (!udpclient.UdpActive) //{ // UDPClientDisConnectedEvent(this, udpclient.UdpActive); //} byte[] rcvBuffer = null; rcvBuffer = udpclient.Receive(ref remoteCLIPE); if (rcvBuffer.Length > 0) { //rcvMsg = null; //switch (SocketMsgKinds) //{ // case MsgKinds.CommandMessage: // rcvMsg = util.GetObject<CommandMsg>(rcvBuffer); // break; // case MsgKinds.SMSMessage: // break; // case MsgKinds.GroupWareMessage: // break; // case MsgKinds.CdrRequest: // rcvMsg = util.GetObject<CdrRequest_t>(rcvBuffer); // break; // case MsgKinds.RecordInfo: // rcvMsg = util.GetObject<RecordInfo_t>(rcvBuffer); // break; //} //if (UDPClientEventReceiveMessage != null) // UDPClientEventReceiveMessage(this, rcvMsg); if (UDPClientEventReceiveMessage != null) { UDPClientEventReceiveMessage(this, rcvBuffer); } } Thread.Sleep(0); } } catch (System.Net.Sockets.SocketException se) { this.Stop(); MessageBox.Show(se.ErrorCode + " : " + se.Message); //throw se; } }
private void SendReceiveMsg() { try { remoteCLIPE = new IPEndPoint(IPAddress.Any, 0); while (_IsStarted) { byte[] rcvBuffer = null; rcvBuffer = udpclient.Receive(ref remoteCLIPE); if (rcvBuffer.Length > 0) { rcvMsg = null; switch (SocketMsgKinds) { case MsgKinds.CommandMessage: rcvMsg = util.GetObject <CommandMsg>(rcvBuffer); break; case MsgKinds.SMSMessage: break; case MsgKinds.GroupWareMessage: break; case MsgKinds.CdrRequest: rcvMsg = util.GetObject <CdrRequest_t>(rcvBuffer); break; case MsgKinds.RecordInfo: rcvMsg = util.GetObject <RecordInfo_t>(rcvBuffer); break; } if (UDPClientEventReceiveMessage != null) { UDPClientEventReceiveMessage(this, rcvMsg); } } Thread.Sleep(0); } } catch (System.Net.Sockets.SocketException se) { this.Stop(); //MessageBox.Show(se.ErrorCode + " : " + se.Message); //throw se; util.WriteLog(string.Format("{0} : {1}", se.ErrorCode, se.Message)); } }
private void btnRecieve_Click(object sender, EventArgs e) { IPEndPoint host = new IPEndPoint(IPAddress.Any, 0); System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient(int.Parse(tbxPort.Text)); byte[] message = client.Receive(ref host); tbxMessage.Text += DateTime.Now.ToString("h:mm:ss tt") + ": " + Encoding.Unicode.GetString(message); tbxMessage.Text += Environment.NewLine; client.Dispose(); }
/// <summary> /// /// </summary> private void ThreadPro() { while (!mIsClosed) { if (mClient != null && mClient.Client.Available > 0 && !mIsTransparentRead) { var vdata = mClient.Receive(ref rp); if (mForSyncCall) { lock (mLockObj) { mReceiveDataLen += vdata.Length; mReceiveBuffers.Enqueue(vdata); } } else { OnReceiveCallBack("", vdata); } } Thread.Sleep(1); } }
private void ReceiveImage() { IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { lock (locker) { try { Byte[] receiveBytes = receivingUdpClient.Receive(ref remoteIpEndPoint); var op = _udpHelper.PackageConcat(receiveBytes); if (op == 0) { Dispatcher.Invoke(() => { //LbReceive.Content = $"{++count + 1}"; LbReceiveImageProcess.Content = $"{++count}/{UdpHelper.Packages.Count}"; }); } if (op == 1) { var img = _udpHelper.PackageMerge(UdpHelper.Packages, 1); Dispatcher.Invoke(() => { ImageReceive.Source = UdpHelper.BytesToBitmapImage(img); count = 0; }); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } } }
private void Rec() { try { System.Net.IPEndPoint remoteendpoint = new System.Net.IPEndPoint(IPAddress.Any, port); while (true) { var bytes = client.Receive(ref remoteendpoint); Task.Run(() => { var entity = SerializeHelper.Deserialize(bytes) as UDPMsgEntity; if (entity != null) { var rec = System.Text.Encoding.UTF8.GetString(bytes); Console.WriteLine(string.Join <IPAddress>(",", entity.IPs)); var reip = remoteendpoint.Address.ToString(); //if (reip != "127.0.0.1") { if (entity.MsgType == 0) { Sysconstant.AddRemotePoint(remoteendpoint.Address); log.Log.WriteLog("收到数据包:" + reip); } if (entity.MsgType == 1) { MyMessage.NewMsg(new Msg() { msg = entity.Msg, MsgType = Definition.MsgType.Txt, IpAddress = remoteendpoint.Address }); } } } else { } }); } } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.ToString()); //if (ErrorEvent != null) //{ // ErrorEvent(null, ex.ToString()); //} log.Log.WriteLog(ex.ToString()); } }
private void Update() { //データを受信する System.Net.IPEndPoint remoteEP = null; byte[] rcvBytes = udp.Receive(ref remoteEP); //データを文字列に変換する string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes); //受信したデータと送信者の情報を表示する Debug.Log("受信したデータ: " + rcvMsg); Debug.Log("送信元アドレス: " + remoteEP.Address + ",ポート番号: " + remoteEP.Port); uDPBlendShapeVisualizer.Renering(rcvMsg); }
static void UdpServer(String server, int port) { // UDP 서버 작성 System.Net.Sockets.UdpClient udpServer = new System.Net.Sockets.UdpClient(port); try { //IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { Console.WriteLine("수신 대기..."); IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = udpServer.Receive(ref remoteIpEndPoint); string returnData = System.Text.Encoding.GetEncoding(932).GetString(receiveBytes); // 수신 데이터와 보낸 곳 정보 표사 Console.WriteLine("수신: {0}Bytes {1}", receiveBytes.Length, returnData); Console.WriteLine("보낸 곳 IP=" + remoteIpEndPoint.Address.ToString() + " 포트 번호= " + remoteIpEndPoint.Port.ToString()); // 수신 데이터를 대문자로 변환하여 보낸다. returnData = returnData.ToUpper(); byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(returnData); // UTF8 // 보낸 곳에 답변 Console.WriteLine("답변 데이터: {0}bytes {1}", sendBytes.Length, returnData); udpServer.Send(sendBytes, sendBytes.Length, remoteIpEndPoint); } } catch (Exception e) { Console.WriteLine(e.ToString()); } udpServer.Close(); Console.Read(); }
/// <summary> /// Returns a UDP datagram that was sent by a remote host. /// </summary> /// <param name="tempClient">UDP client instance to use to receive the datagram</param> /// <param name="packet">Instance of the recieved datagram packet</param> public static void Receive(System.Net.Sockets.UdpClient tempClient, out PacketSupport packet) { System.Net.IPEndPoint remoteIpEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0); PacketSupport tempPacket; try { byte[] data_in = tempClient.Receive(ref remoteIpEndPoint); tempPacket = new PacketSupport(data_in, data_in.Length); tempPacket.IPEndPoint = remoteIpEndPoint; } catch (System.Exception e) { throw new System.Exception(e.Message); } packet = tempPacket; }
private void ListenHandler() { var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Any, UDPPort); byte[] buffer = null; while (IsListening) { System.Threading.Thread.Sleep(1000); try { buffer = UdpClient.Receive(ref epGroup); } catch { } if (buffer == null || buffer.Length < 1) { continue; } var msg = System.Text.Encoding.UTF8.GetString(buffer); if (msg.Length > 0) { Owner.Invoke(DgGetMsg, msg); } } }
public void UdpSocketReceiveStart(Action <IPEndPoint, byte[]> action) { System.Net.IPEndPoint remoteEP = null; socketReceiveThread = new Thread(() => { while (true) { byte[] receiveBytes = udpClient.Receive(ref remoteEP); Console.WriteLine("{0} {1}", remoteEP.Address, remoteEP.Port); action(remoteEP, receiveBytes); //Environment.Exit(0); } }); socketReceiveThread.IsBackground = true; socketReceiveThread.Start(); //udpClient.Close(); }
private void Listen() { try { udpClient = new System.Net.Sockets.UdpClient(editorModeUDPPort); print("Started UDP client on port: " + editorModeUDPPort); while (true) { // receive bytes byte[] data = udpClient.Receive(ref _remoteEndPoint); if (ExecuteOnMainThread.Count == 0) { ExecuteOnMainThread.Enqueue(() => { InterpreteUDPData(data); }); } } } catch (Exception err) { print(err.ToString()); } }
public void serverThread() { try { System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(constants.SERVER_PORT_UDP); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); byte[] data = new byte[1024]; data = udpClient.Receive(ref sender); udpClient.Close(); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); server.GlassIP = sender.Address.ToString(); server.udpServer = new UdpClient(constants.SERVER_PORT_UDP_GAZE); server.remoteEP = new IPEndPoint(IPAddress.Parse(server.GlassIP), constants.SERVER_PORT_UDP_GAZE); server.sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); METState.Current.METCoreObject.SendToForm("Glass IP: " + server.GlassIP + "\r\n", "tbOutput"); } catch (Exception e) { } }
}//end Server public void udpReceiverThread() { try { System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(1234); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); do { byte[] data = new byte[1024]; data = udpClient.Receive(ref sender); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine("....................." + stringData); if (stringData == "t") { METState.Current.timeDifference = METState.Current.recording_timer.ElapsedMilliseconds / 2; Console.WriteLine("..........Delay is ..........." + (METState.Current.recording_timer.ElapsedMilliseconds / 2).ToString()); METState.Current.recording_timer.Restart(); int udp_port = 9876; System.Net.Sockets.UdpClient udpServer = new System.Net.Sockets.UdpClient(udp_port); System.Net.IPEndPoint remoteEP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(METState.Current.tempUDPClient_ip), udp_port); byte[] packed = System.Text.Encoding.ASCII.GetBytes("s\n"); udpServer.Send(packed, packed.Length, remoteEP); Console.WriteLine("..................... s sent to client"); udpServer.Close(); } }while (true); } catch (Exception e) { } }
/// <summary> /// 监听方法 /// </summary> private void ListenHandler() { var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 2425); UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000); byte[] buffer = null; while (IsListening) { System.Threading.Thread.Sleep(20); try { buffer = UdpClient.Receive(ref epGroup); } catch (Exception) { } if (buffer == null || buffer.Length < 1) { continue; } var msg = System.Text.Encoding.Default.GetString(buffer); var ip = epGroup.Address.ToString(); Thread listendthread = new Thread(listendThread); ListenedPara para = new ListenedPara(); para.Ip = ip; para.Msg = msg; listendthread.Start(para); } }
static void Main(string[] args) { ConsoleKeyInfo cki; Console.WriteLine("Esperando conexiones"); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); int i = 0; List <IPAddress> direcciones = new List <IPAddress>(); Boolean flag = true; while (flag) { System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(3000); byte[] data = new byte[1024]; data = server.Receive(ref sender); server.Close(); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine("Respondiendo desde " + sender.Address + Environment.NewLine + "Mensaje: " + stringData); Console.WriteLine(); direcciones.Add(sender.Address); Console.WriteLine("Deseas esperar otra conexion? Y/N"); cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.N) { flag = false; } else { Console.WriteLine("Esperando otra conexion"); Console.WriteLine(""); } } Console.WriteLine("Escribe la direccion y el rango de puertos a escanear, ejemplo: 192.168.1.1 1-25"); String texto = Console.ReadLine(); string[] aux = texto.Split(' '); IPAddress direccion = IPAddress.Parse(aux[0]); String[] puertos = aux[1].Split('-'); int pInicial = Int32.Parse(puertos[0]); int pFinal = Int32.Parse(puertos[1]); try { if (direcciones.Count > 0) //if (true) { //int total = direcciones.Count; int rango = ((pFinal - pInicial) + 1) / (direcciones.Count + 1); foreach (IPAddress d in direcciones) { int pf = pInicial + rango; String scan = direccion + " " + pInicial + "-" + pf; Console.WriteLine(scan); string result = Cliente(d, scan); Console.WriteLine(result); pInicial = pf + 1; } for (int CurrPort = pInicial; CurrPort <= pFinal; CurrPort++) { TcpClient TcpScan = new TcpClient(); try { TcpScan.Connect(direccion, CurrPort); Console.WriteLine("Port " + CurrPort + " open"); } catch { Console.WriteLine("Port " + CurrPort + " closed"); } } } else { for (int CurrPort = pInicial; CurrPort <= pFinal; CurrPort++) { TcpClient TcpScan = new TcpClient(); try { TcpScan.Connect(direccion, CurrPort); Console.WriteLine("Port " + CurrPort + " open"); } catch { Console.WriteLine("Port " + CurrPort + " closed"); } } } } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); }
static void Main(string[] args) { System.Net.Sockets.UdpClient sock = new System.Net.Sockets.UdpClient(); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("129.241.187.44"), 20004); Console.WriteLine("Enter message"); string userinput = Console.ReadLine(); byte[] data = Encoding.ASCII.GetBytes(userinput); sock.Send(data, data.Length, iep); sock.Close(); Console.WriteLine("Message sent."); System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(20004); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); byte[] recvdata = new byte[1024]; recvdata = server.Receive(ref sender); server.Close(); string stringData = Encoding.ASCII.GetString(recvdata, 0, recvdata.Length); Console.WriteLine("Response from " + sender.Address + Environment.NewLine + "Message: " + stringData); Console.ReadLine(); }