public static DiscoveryResult DiscoverDevice(int port) { IEnumerable<string> ips = getInterfaceAddresses(); var ret = new DiscoveryResult(); _localEndPoint = new IPEndPoint(IPAddress.Any, 0); _client = new UdpClient(port); var p = new ISCPPacket("!xECNQSTN"); byte[] sendbuf = p.GetBytes(); foreach (string networkaddress in ips) { _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port); _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port); _client.Send(sendbuf, sendbuf.Length, IPAddress.Parse(networkaddress).ToString(), port); } while (_client.Available > 0) { byte[] recv = _client.Receive(ref _localEndPoint); Thread.Sleep(100); var sb = new StringBuilder(); foreach (byte t in recv) sb.Append(char.ConvertFromUtf32(Convert.ToInt32(string.Format("{0:x2}", t), 16))); string stringData = sb.ToString(); if (stringData.Contains("!1ECN")) { int idx = stringData.IndexOf("!1ECN") + 5; string[] parts = stringData.Substring(idx).Split('/'); string mac = parts[3].Substring(0,12); string ip = ARP.GetIPInfo(mac).IPAddress; ret.IP = ip; ret.Port = Convert.ToInt32(parts[1]); ret.Region = stringData.Substring(idx + 14, 2); ret.MAC = mac; ret.Model = stringData.Substring(idx, 7); } } _client.Close(); return ret; }
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); } } }
protected override void Loop(CancellationToken token) { int sequenceNumber = 1; ConcurrentQueueHelper.Flush(_commandQueue); using (var udpClient = new UdpClient(CommandPort)) { udpClient.Connect(_configuration.DroneHostname, CommandPort); byte[] firstMessage = BitConverter.GetBytes(1); udpClient.Send(firstMessage, firstMessage.Length); Stopwatch swKeepAlive = Stopwatch.StartNew(); while (token.IsCancellationRequested == false) { ATCommand command; if (_commandQueue.TryDequeue(out command)) { byte[] payload = command.CreatePayload(sequenceNumber); Trace.WriteIf((command is COMWDGCommand) == false, Encoding.ASCII.GetString(payload)); udpClient.Send(payload, payload.Length); sequenceNumber++; swKeepAlive.Restart(); } else if (swKeepAlive.ElapsedMilliseconds > KeepAliveTimeout) { _commandQueue.Enqueue(new COMWDGCommand()); } Thread.Sleep(1); } } }
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); } }
public override void Send(string serverHostName, string serverIpAddress, int serverPort, string message) { var ipAddress = IPAddress.Parse(serverIpAddress); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, serverPort); using(UdpClient udpClient = new UdpClient()){ var gzipMessage = GzipMessage(message); if (MaxChunkSize < gzipMessage.Length) { var chunkCount = gzipMessage.Length / MaxChunkSize + 1; var messageId = GenerateMessageId(serverHostName); for (int i = 0; i < chunkCount; i++) { var messageChunkPrefix = CreateChunkedMessagePart(messageId, i, chunkCount); var skip = i * MaxChunkSize; var messageChunkSuffix = gzipMessage.Skip(skip).Take(MaxChunkSize).ToArray<byte>(); var messageChunkFull = new byte[messageChunkPrefix.Length + messageChunkSuffix.Length]; messageChunkPrefix.CopyTo(messageChunkFull, 0); messageChunkSuffix.CopyTo(messageChunkFull, messageChunkPrefix.Length); udpClient.Send(messageChunkFull, messageChunkFull.Length, ipEndPoint); } } else { udpClient.Send(gzipMessage, gzipMessage.Length, ipEndPoint); } } }
/* sign blink */ static void Indicate(string name, int score) { const int LED_COUNT = 126; UdpClient client = new UdpClient(); /* blue */ byte[] data = new byte[LED_COUNT * 3]; for (int i = 0; i < LED_COUNT; i++) { data[i * 3 + 0] = 0x80 + 30; data[i * 3 + 1] = 0x80; data[i * 3 + 2] = 0x80; } client.Send(data, data.Length, "schild", 10002); System.Threading.Thread.Sleep(50); /* blank */ for (int i = 0; i < LED_COUNT; i++) { data[i * 3 + 0] = 0x80; data[i * 3 + 1] = 0x80; data[i * 3 + 2] = 0x80; } client.Send(data, data.Length, "schild", 10002); }
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); } }
private void SendBordcast(object o) { try { UDPMsgEntity entity = Sysconstant.LocalBordcastEntity; var bytes = SerializeHelper.Serialize(entity); if (!Sysconstant.MutiBordcast) { System.Net.IPEndPoint endpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, port); var count = client.Send(bytes, bytes.Length, endpoint); } else { foreach (IPAddress ip in Sysconstant.LocalIPAddress) { int index = ip.ToString().LastIndexOf("."); string ip1 = ip.ToString().Substring(0, index); string ip2 = ip1 + ".255"; IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ip2), port); var count = client.Send(bytes, bytes.Length, endpoint); } } } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.ToString()); //if (ErrorEvent != null) //{ // ErrorEvent(null, ex.ToString()); //} log.Log.WriteLog(ex.ToString()); } }
public Sender(String sprava, String ipString, String portString, String rozlozenieString) { int port; IPAddress ip; if(IPAddress.TryParse(ipString,out ip) == false) { return; } if(Int32.TryParse(portString,out port) == false) { return; } int maxVelkost = Int32.MaxValue; if (Int32.TryParse(rozlozenieString, out maxVelkost) == false) { return; } UdpClient client = new UdpClient(); int i = 0; int pocet = (sprava.Length + maxVelkost -1)/ (maxVelkost) + 1 ; MessageBox.Show("Počet odoslanych sprav je: " + pocet,"Info", MessageBoxButtons.OK, MessageBoxIcon.Information); String pocetString = "0000" + pocet.ToString("D4"); try { client.Send(Encoding.ASCII.GetBytes(pocetString), pocetString.Length, ip.ToString(), port); } catch (Exception ex) { Console.WriteLine("chyba: " + ex.Message); } for (i = 1; i < pocet; i++) { String poradieString = i.ToString("D4"); int koniec = 0; if (i * maxVelkost > sprava.Length) { koniec = sprava.Length - (i-1)*maxVelkost; } else { koniec = maxVelkost; } Byte[] data = Encoding.ASCII.GetBytes(poradieString + sprava.Substring((i-1)*maxVelkost,koniec)); try { client.Send(data, data.Length, ip.ToString(), port); } catch (Exception ex) { Console.WriteLine("chyba: " + ex.Message); } } client.Close(); }
public void UdpSocketSend(IPEndPoint iPEndPoint, byte[] data) { if (isServerOver) { data = new byte[] { 11 }.Concat(data).ToArray(); iPEndPoint = serverIPEndPoint; } udpClient.Send(data, data.Length, iPEndPoint); }
public void Search() { ISearchResponseParser searchResponseParser = new SimpleSearchResponseParser(); var sb = new StringBuilder(); sb.AppendLine("M-SEARCH * HTTP/1.1"); sb.AppendLine("HOST:239.255.255.250:1900"); sb.AppendLine("MAN:\"ssdp:discover\""); //sb.AppendLine("ST:ssdp:all"); sb.AppendLine("ST: urn:schemas-upnp-org:device:ZonePlayer:1"); sb.AppendLine("MX:3"); sb.AppendLine(""); var searchString = sb.ToString(); var data = Encoding.UTF8.GetBytes(searchString); udpClient = new UdpClient(); //udpClient.Connect("239.255.255.250", 1900); udpClient.Send(data, data.Length, "239.255.255.250", 1900); udpClient.Send(data, data.Length, "255.255.255.255", 1900); Console.WriteLine("M-Search sent... \r\n"); var timeoutTime = DateTime.UtcNow.Add(searchTimeOut); searching = true; while (searching) { if (DateTime.UtcNow > timeoutTime) { Console.WriteLine("Search Timeout Reached. Starting a new search."); //udpSocket.Close(); //udpSocket.Dispose(); // Note: this might cause a stack overflow exception because we are recursivley calling this over and over. // should probably refactor this to use an external timer that starts and stops / disposes. Search(); } if (udpClient.Client.Available > 0) { var receiveBuffer = new byte[udpClient.Client.Available]; var receivedBytes = udpClient.Client.Receive(receiveBuffer, SocketFlags.None); if (receivedBytes > 0) { var characters = Encoding.UTF8.GetChars(receiveBuffer); var s = new string(characters); var serviceDescription = searchResponseParser.Parse(s); if (ServiceDiscovered != null) ServiceDiscovered(serviceDescription); } } Thread.Sleep(100); //UdpSocket.SendTo(Encoding.UTF8.GetBytes(searchString), SocketFlags.None, MulticastEndPoint); } }
protected virtual void ReceiveConnect(ConnectMessage connectMessage) { UdpTrackerMessage m = new ConnectResponseMessage(connectMessage.TransactionId, CreateConnectionID()); byte[] data = m.Encode(); #if NETSTANDARD1_5 listener.SendAsync(data, data.Length, endpoint); #else listener.Send(data, data.Length, endpoint); #endif }
public void Send(byte st) { msg = GetCommandMsg(st); byte[] bytes = util.GetBytes(msg); try { udpclient.Send(bytes, bytes.Length); } catch (System.Net.Sockets.SocketException ex) { throw ex; } }
public void Send(byte st) { msg = GetCommandMsg(st); byte[] bytes = util.GetBytes(msg); try { udpclient.Send(bytes, bytes.Length); } catch (System.Net.Sockets.SocketException ex) { //throw ex; util.WriteLog(string.Format("{0} : {1}", ex.ErrorCode, ex.Message)); } }
public void TestUDPPacket() { SharpNet.OnReceiveUDPPacketHandler Handler = async(UDPPacket Packet) => { if (Packet.DestPort == remotePort) { UDPPacket echo = new UDPPacket(new byte[] { 1, 2, 3, 4, 5 }); echo.SourceIP = Packet.DestIP; echo.DestIP = Packet.SourceIP; echo.SourcePort = Packet.DestPort; echo.DestPort = Packet.SourcePort; await net.SendIPPacketAsync(echo); } }; net.OnReceiveUDPPacket += Handler; CancellationTokenSource cts = new CancellationTokenSource(); int tx = 0; int rx = 0; Task.Run(() => { while (true) { //byte[] data = client.Receive(ref remote); byte[] data = client.ReceiveAsync().Result.Buffer; foreach (var d in data) { Trace.Write(d); } rx++; } }, cts.Token); Task.Run(() => { while (true) { client.Send(new byte[] { 1, 2, 3, 4 }, 4, remote); tx++; Task.Delay(500).Wait(); } }, cts.Token); Task.Delay(5000).Wait(); cts.Cancel(); net.OnReceiveUDPPacket -= Handler; Assert.IsTrue((rx == tx) && (rx != 0), "Send echo back received number does not match"); }
private static void Send(string datagram) { // Создаем UdpClient UdpClient sender = new UdpClient(); // Создаем endPoint по информации об удаленном хосте IPEndPoint endPoint = new IPEndPoint(remoteIPAddress, remotePort); try { // Преобразуем данные в массив байтов byte[] bytes = Encoding.UTF8.GetBytes(datagram); // Отправляем данные sender.Send(bytes, bytes.Length, endPoint); } catch (Exception ex) { Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n " + ex.Message); } finally { // Закрыть соединение sender.Close(); } }
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; } } }
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); } }
/// <summary> /// broadcast a message to others /// </summary> /// <param name="msg"></param> public void Broadcast(string msg) { var epGroup = new System.Net.IPEndPoint(GroupIP, UDPPort); var buffer = System.Text.Encoding.UTF8.GetBytes(msg); UdpClient.Send(buffer, buffer.Length, epGroup); }
public override void SendSipMsgToClient(string sipMsg, NET.IPEndPoint clientEp) { if (null == sipMsg) { throw new ArgumentNullException("sipMsg"); } if (null == clientEp) { throw new ArgumentNullException("clientEp"); } if (0 == sipMsg.Length) { return; } m_Settings.WriteMessageToLog( LogMessageType.Information + 2, string.Format( CultureInfo.CurrentUICulture, "Sending SIP message to {0}:{1}\n{2}", clientEp.Address, clientEp.Port, sipMsg ) ); byte[] data = g_Ascii.GetBytes(sipMsg); m_udpClient.Send(data, data.Length, clientEp); }
/// <summary> /// Функция-обработчик потока /// </summary> protected void doThread() { UdpClient udpClient = new UdpClient(); try { IsWorking = true; byte[] bytes = Encoding.UTF8.GetBytes("<server-request>"); List<IPAddress> broadcastIp = AddressProvider.GetBroadcastIp(); while (mustWork) { foreach (IPAddress ip in broadcastIp) { IPEndPoint endPoint = new IPEndPoint(ip, 11000); udpClient.Send(bytes, bytes.Length, endPoint); } Thread.Sleep(1000); } } catch (ExceptionServer e) { } finally { IsWorking = false; } }
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)); } }
private static bool trySendUdp(UdpClient s, string hostname, int size) { byte[] b = new byte[size]; try { s.Send(b, size, hostname, 1234); } catch (SocketException) { return false; } return true; }
public void Run() { udpclient = new UdpClient(); collector = new Collector(countersInfo); startedEvent.Set(); while (continueProcess) { try { byte[] sendBytes = collector.CollectInfoForAllCounters(); //ShowBytes(sendBytes); udpclient.Send(sendBytes, sendBytes.Length, endPoint); } catch (NullReferenceException ex) { Trace.TraceError("SendBytes array is null, {0}", ex.ToString()); } catch (SocketException ex) { Trace.TraceError("Socket error mesage: {0}, code: {1}", ex.Message, ex.ErrorCode); } Thread.Sleep(DataSendInterval); } }
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); } }
private static void StartPerfmonCollectionLoop() { var counters = new PerformanceCounters(""); var syslogForwarder = new UdpClient(); syslogForwarder.Connect(ConfigurationManager.AppSettings["forward_host"], int.Parse(ConfigurationManager.AppSettings["forward_port"])); var sw = Stopwatch.StartNew(); while (true) { sw.Restart(); foreach (var counter in counters) { var nextValue = counter.NextValue(); var timestamp = DateTime.Now; var datagram = GetSyslogDatagram(counter, nextValue, timestamp); var bytesSend = syslogForwarder.Send(datagram, datagram.Length); log.Debug("Sending " + datagram.Length + " bytes"); if (bytesSend != datagram.Length) { log.ErrorFormat("bytes sent " + bytesSend + " does not equal datagram length " + datagram.Length); } } sw.Stop(); log.Info(string.Format("Queried {0} counters in {1} ms", counters.Count, sw.Elapsed.TotalMilliseconds)); Thread.Sleep(10 * 1000); } }
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 StartAnnouncing() { Task.Factory.StartNew(() => { try { CancellationToken token = cts.Token; logger.Trace("Start announcing"); using (var client = new UdpClient()) { var ip = new IPEndPoint(IPAddress.Broadcast, 15000); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); while (true) { token.ThrowIfCancellationRequested(); byte[] bytes = Encoding.ASCII.GetBytes("MonoServer"); client.Send(bytes, bytes.Length, ip); Thread.Sleep(100); } } } catch (OperationCanceledException) { } catch (Exception ex) { logger.Trace(ex); } }); }
private void buttonApply_Click(object sender, EventArgs e) { UdpClient udpClient = new UdpClient(); udpClient.Connect(TextBoxIPComputer.Text, SERVER_PORT); Byte[] senddata = Encoding.ASCII.GetBytes("sync " + DateTime.UtcNow.ToString()); udpClient.Send(senddata, senddata.Length); }
//metoda koja šalje poruku čvoru koji sadrži traženu datoteku public void connect(string destination, string fileName, string udpPort) { ip = destination; this.fileToDownload = fileName; //kreiranje polja bajtova u koje se spremaju podaci koji se šalju korisniku //(ime datoteke, veličina datoteke i veličina imena) byte[] data = new byte[4096]; try { //dohvaćanje porta na koji se šalju podaci int portNumber = Convert.ToInt32(udpPort); //parsiranje IP adrese iz stringa ip = ip.Replace(" ", string.Empty); IPAddress ipaddr = IPAddress.Parse(this.ip); //kreiranje UDP klijenta i IPEndPointa koji šalju podatke UdpClient server = new UdpClient(); IPEndPoint sender = new IPEndPoint(ipaddr, portNumber); //kreiranje poruke koja se šalje i njeno kodiranje u bajtove string welcome = "D" + helper.portTCP + ":" + this.fileToDownload; data = Encoding.ASCII.GetBytes(welcome); //slanje poruke (podaci, veličina podataka, podaci o računalu) server.Send(data, data.Length, sender); } //hvatanje izinmke catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } }
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 static void SendMessage(byte[] data, HostInfo hostInfo, IMessageSerializer messageSerializer) { //IPHostEntry hostEntry = Dns.GetHostEntry(hostInfo.Hostname); //IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], hostInfo.Port); //Socket s = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); //s.SendTo(data, endPoint); //s.Close(); short netProtocolType = IPAddress.HostToNetworkOrder(messageSerializer.ProtocolType); short netProtocolVersion = IPAddress.HostToNetworkOrder(messageSerializer.ProtocolVersion); int netMessageLength = IPAddress.HostToNetworkOrder(data.Length); byte[] netProtocolTypeData = BitConverter.GetBytes(netProtocolType); byte[] netProtocolVersionData = BitConverter.GetBytes(netProtocolVersion); byte[] netMessageLengthData = BitConverter.GetBytes(netMessageLength); byte[] mergedData = new byte[netProtocolTypeData.Length + netProtocolVersionData.Length + netMessageLengthData.Length + data.Length]; // Header Array.Copy(netProtocolTypeData, 0, mergedData, 0, netProtocolTypeData.Length); Array.Copy(netProtocolVersionData, 0, mergedData, netProtocolTypeData.Length, netProtocolVersionData.Length); Array.Copy(netMessageLengthData, 0, mergedData, netProtocolTypeData.Length + netProtocolVersionData.Length, netMessageLengthData.Length); // Data Array.Copy(data, 0, mergedData, netProtocolTypeData.Length + netProtocolVersionData.Length + netMessageLengthData.Length, data.Length); UdpClient client = new UdpClient(); client.Send(mergedData, mergedData.Length, hostInfo.Hostname, hostInfo.Port); client.Close(); }
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; }
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"); } }
/// <summary> /// send to specific addresss /// </summary> /// <param name="bytes"></param> /// <param name="address"></param> protected void SendRaw(byte[] bytes,string address) { using (var client = new UdpClient()) { client.Send(bytes, bytes.Length, address, Listener.PORT); } }
public void Send(byte[] datagram, int bytes, IPEndPoint ipEndPoint) { using (var udpClient = new UdpClient()) { udpClient.Send(datagram, bytes, ipEndPoint); } }
private void frmMain_FormClosed(object sender, FormClosedEventArgs e) { UdpClient uc = new UdpClient(); string msg = "LOGOUT"; byte[] bmsg = Encoding.Default.GetBytes(msg); uc.Send(bmsg, bmsg.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 9527)); }
public static void Send(IPAddress source, IPAddress destination, string verb, int fingerprint) { using (UdpClient client = new UdpClient(new IPEndPoint(source, 0))) { Data.Packet packet = new Data.Packet(); packet.MachineName = Environment.MachineName; packet.Fingerprint = fingerprint; packet.Verb = verb; JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonData = serializer.Serialize(packet); byte[] bytes = Encoding.ASCII.GetBytes(jsonData); IPEndPoint ip = new IPEndPoint(destination, Config.Port); try { client.Send(bytes, bytes.Length, ip); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.HostUnreachable) //reasoning: we broadcast on all interfaces //on OS X this may result in No route to host Console.WriteLine(String.Format("{0}: {1}", source, ex.Message)); else throw; } finally { client.Close(); } } }
public int Send(string sourceIp, string targetIp, int udpPort, TimeSpan delay, TimeSpan duration, List<string> source) { var start = DateTime.UtcNow; var localCounter = 0; using (var UC = new UdpClient(new IPEndPoint(IPAddress.Parse(sourceIp), 0))) { while (DateTime.UtcNow < start.Add(duration)) { var txtMsg = source[localCounter % source.Count]; var msg = Encoding.ASCII.GetBytes(txtMsg); var defMatch = SyslogParser.DefaultParser.Match(txtMsg); var privalMatch = defMatch.Groups["PRIVAL"].Value.Trim(); var prival = int.Parse(privalMatch); var sent = new SimpleTxSyslog() { Sev = (Severity)Enum.ToObject(typeof(Severity), prival & 0x7), Fac = (Facility)Enum.ToObject(typeof(Facility), prival >> 3), Message = defMatch.Groups["MESSAGE"].Value.Trim(), }; this.SentList.Add(sent); UC.Send(msg, msg.Length, targetIp, udpPort); localCounter++; Thread.Sleep(delay); } } return localCounter; }
public static void SendData(Program ProgramCur,Patient pat) { if(pat==null) { MsgBox.Show("EvaSoft","You must select a patient first."); return; } Process[] evaSoftInstances=Process.GetProcessesByName("EvaSoft"); if(evaSoftInstances.Length==0) { MsgBox.Show("EvaSoft","EvaSoft is not running. EvaSoft must be running before the bridge will work."); return; } ArrayList ForProgram=ProgramProperties.GetForProgram(ProgramCur.ProgramNum); UdpClient udpClient=new UdpClient(); string udpMessage="REQUEST01123581321~~~0.1b~~~pmaddpatient~~~"; //Patient id can be any string format ProgramProperty PPCur=ProgramProperties.GetCur(ForProgram,"Enter 0 to use PatientNum, or 1 to use ChartNum"); if(PPCur.PropertyValue=="0") { udpMessage+=pat.PatNum.ToString(); } else { udpMessage+=pat.ChartNumber.Replace(",","").Trim();//Remove any commas. Not likely to exist, but just to be safe. } udpMessage+=","+pat.FName.Replace(",","").Trim();//Remove commas from data, because they are the separator. udpMessage+=","+pat.LName.Replace(",","").Trim();//Remove commas from data, because they are the separator. udpMessage+=","+pat.Birthdate.ToString("MM/dd/yyyy"); udpMessage+=","+((pat.Gender==PatientGender.Female)?"female":"male"); udpMessage+=","+(pat.Address+" "+pat.Address2).Replace(",","").Trim();//Remove commas from data, because they are the separator. udpMessage+=","+pat.City.Replace(",","").Trim();//Remove commas from data, because they are the separator. udpMessage+=","+pat.State.Replace(",","").Trim();//Remove commas from data, because they are the separator. udpMessage+=","+pat.Zip.Replace(",","").Trim();//Remove commas from data, because they are the separator. byte[] udpMessageBytes=Encoding.ASCII.GetBytes(udpMessage); udpClient.Send(udpMessageBytes,udpMessageBytes.Length,"localhost",35678); }
/// <summary> /// 回复握手消息 /// </summary> public void SendResponeShakeHandToSomeIP(string ip, string msgbody) { //this.msgtype = FeiQIM.MsgType.OnLine.ToString(); string msg = String.Format(MsgHeader, feiQHead, MsgId, userName, hostName, MsgType.ResponeShakeHand.ToString("D")) + msgbody; var SendIp = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), uDPPort); var buffer = System.Text.Encoding.Default.GetBytes(msg); UdpClient.Send(buffer, buffer.Length, SendIp); }
public void SendCommand() { _udpClient.Connect(_hostIp, 9000); string cmdToSend = Console.ReadLine(); Byte[] bytesToSend = Encoding.ASCII.GetBytes(cmdToSend); _udpClient.Send(bytesToSend, bytesToSend.Length); }
private void UdpSend(byte[] byteData) { string strDstIP = textBoxDstIp.Text; int sDstPort = Int32.Parse(textBoxDstPort.Text); //リモートホストを指定してデータを送信する m_udp.Send(byteData, byteData.Length, strDstIP, sDstPort); }
/// <summary> /// broadcast a message to others /// </summary> /// <param name="msg"></param> static public void Broadcast(string msg) { var epGroup = new System.Net.IPEndPoint(GroupIP, 1020); var buffer = System.Text.Encoding.UTF8.GetBytes(msg); UdpClient = new System.Net.Sockets.UdpClient(1019); UdpClient.Send(buffer, buffer.Length, epGroup); UdpClient.Close(); }
/// <summary> /// broadcast a message to others /// </summary> /// <param name="msg"></param> static public void Broadcast(string msg, int UDPPort) { var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("224.0.0.2"), UDPPort); var buffer = System.Text.Encoding.UTF8.GetBytes(msg); System.Net.Sockets.UdpClient UdpClient = new System.Net.Sockets.UdpClient(1019); UdpClient.Send(buffer, buffer.Length, epGroup); UdpClient.Close(); }
public void SendSoundDataToServer(byte[] data) { if (null == data) { throw new ArgumentNullException(); } m_udpClient.Send(data, data.Length, m_RemoteEp); }
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()); } }
// send thread private void SendData() { System.Net.Sockets.UdpClient cliente = new System.Net.Sockets.UdpClient(); while (!conectado) { ; } cliente.Connect(anyIP.Address, puerto); qr.endQRShow();//end the QR byte[] timeToVibrate = new byte[4]; timeToVibrate[0] = (byte)(vibrationTime & 0x000000FF); timeToVibrate[1] = (byte)((vibrationTime >> 4) & 0x000000FF); timeToVibrate[2] = (byte)((vibrationTime >> 8) & 0x000000FF); timeToVibrate[3] = (byte)((vibrationTime >> 16) & 0x000000FF); cliente.Send(timeToVibrate, timeToVibrate.Length); while (sending) { if (vibrate) { byte[] vibrateMessage = new byte[4]; vibrateMessage[0] = 0; vibrateMessage[1] = 0; vibrate = false; cliente.Send(vibrateMessage, vibrateMessage.Length); } if (send) { send = false; cliente.Send(byteImg, byteImg.Length); //este mensaje tiene de latencia 5ms aprox cuando hace ping } } byte[] sendData = new byte[1]; //fin de comunicación sendData[0] = 1; cliente.Send(sendData, sendData.Length); Debug.Log("terminó"); }
public void SendUDPMessage(byte[] data) { try { udpClient.Send(data, data.Length, remoteEndPoint); } catch (Exception e) { UnityEngine.Debug.Log(e.ToString()); } }
static public void BroadcastToFQ(string msg, string ip) { var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), 2425); msg = "1_lbt4_09#65664#206服务器#0#0#0:1289671407:飞秋1号小月月:更新包监控及测试:288:" + msg; var buffer = System.Text.Encoding.Default.GetBytes(msg); UdpClient = new System.Net.Sockets.UdpClient(2426); UdpClient.Send(buffer, buffer.Length, epGroup); UdpClient.Close(); }
/// <summary> /// Send data packet synchronously /// </summary> /// <param name="messageBytes"></param> /// <param name="sendTo"></param> /// <returns></returns> public int Send(byte[] messageBytes, IPEndPoint sendTo) { int ret = 0; if (messageBytes != null) { ret = _udpClient.Send(messageBytes, messageBytes.Length, sendTo); } OnSendCompleted(); return(ret); }
// Update is called once per frame void Update() { _nextTimeToSend -= Time.deltaTime; if (_nextTimeToSend < 0.0f) { _nextTimeToSend += _interval; byte[] byteArray = BitConverter.GetBytes(Time.time); udp.Send(byteArray, byteArray.Length); Debug.Log(string.Format("send: {0}", Time.time)); } }
public static void SendBroadCast(byte[] buffer, int port) { IPEndPoint BroadCastEP = new IPEndPoint(IPAddress.Broadcast, port); foreach (var ep in LocalEPs) { System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(ep); udp.EnableBroadcast = true; udp.Send(buffer, buffer.Length, BroadCastEP); udp.Close(); } }
// PID data送信ルーチン private void Pid_Data_Send() { // PID data send for UDP //データを送信するリモートホストとポート番号 string remoteHost = mmFsiSC440; int remotePort = mmFsiUdpPortSpCam; // KV1000SpCam //送信するデータを読み込む ++(pid_data.id); //pid_data.swid = (ushort)mmFsiUdpPortMT3IDS2s;// 24417; //mmFsiUdpPortMT3WideS pid_data.swid = (ushort)id; // mmFsiUdpPortMT3IDS2s;// 24417; //mmFsiUdpPortMT3WideS pid_data.t = TDateTimeDouble(DateTime.Now); //TDateTimeDouble(imageInfo.TimestampSystem); //LiveStartTime.AddSeconds(CurrentBuffer.SampleEndTime));//(DateTime.Now); if (PvMode == PID_TEST) { xoad = xoa_test_start + xoa_test_step * (pid_data.id - test_start_id); yoad = yoa_test_start + yoa_test_step * (pid_data.id - test_start_id); } else { xoad = xoa_mes; yoad = yoa_mes; } pid_data.dx = (float)(gx - xoad); pid_data.dy = (float)(gy - yoad); pid_data.vmax = (ushort)(max_area); byte[] sendBytes = ToBytes(pid_data); try { //リモートホストを指定してデータを送信する udpc3.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } }
public void Send(string json) { if (string.IsNullOrWhiteSpace(remoteHost)) { return; } byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(json); //リモートホストを指定してデータを送信する udp.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); Debug.Log("送信: " + json); }
// callback for async sending public void Send(byte[] Data, System.Action <bool> OnDataSent = null) { // blocking atm, should make this async/threaded for large data var SentBytes = Socket.Send(Data, Data.Length); if (SentBytes != Data.Length) { throw new System.Exception("Only " + SentBytes + "/" + Data.Length + " bytes sent, todo handle this"); } if (OnDataSent != null) { OnDataSent.Invoke(true); } }
private void ShowButton_Click(object sender, EventArgs e) { /* * if (openFileDialog1.ShowDialog() == DialogResult.OK) * { * pictureBox1.Load(openFileDialog1.FileName); * } */ Pid_Data_Send(); return; //testルーチン double gx = 1; double gy = 2; //PID送信用UDP //バインドするローカルポート番号 FSI_PID_DATA pid_data = new FSI_PID_DATA(); int localPort = 24407; System.Net.Sockets.UdpClient udpc3 = null;; try { udpc3 = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { //匿名デリゲートで表示する this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() }); } //データを送信するリモートホストとポート番号 string remoteHost = "192.168.1.206"; int remotePort = 24410; //送信するデータを読み込む ++(pid_data.id); pid_data.swid = 24402; // 仮 mmFsiUdpPortFSI2 pid_data.t = TDateTimeDouble(DateTime.Now); pid_data.dx = (float)(gx); pid_data.dy = (float)(gy); pid_data.vmax = 123; byte[] sendBytes = ToBytes(pid_data); //リモートホストを指定してデータを送信する udpc3.Send(sendBytes, sendBytes.Length, remoteHost, remotePort); if (udpc3 != null) { udpc3.Close(); } }
void Send(object msg) { try { byte[] sendbytes = encoding.GetBytes(msg.ToString()); udpClient.Send(sendbytes, sendbytes.Length, remoteIpep); } catch (SocketException e) { if (OnError != null) { OnError(e.Message); } } }
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(); }