public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP) { BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished); ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP); UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler UdpServer.JoinMulticastGroup(BroadcastServer.Address); UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null); MaxClients = maxclients; Ip = IPAddress.Any; this.Port = port; listener = new TcpListener(Ip, Port); Clients = new List<ClientContext>(MaxClients); listener.Start(); BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected); this.TextStack = TextStack; }
/* // TODO: Асинхронная отправка! Или не нужно? /// <summary> /// Отправить единичное сообщение на единичный хост /// </summary> /// <param name="text">Текст сообщения</param> // internal static void SendMessage(string RemoteHost, string text) { TcpClient client = null; NetworkStream networkStream = null; try { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000); // TODO : заменить 127.0.0.1 на что-то более верное // TODO: добавить динамическое выделение портов (из пула свободных портов) // получатель сообщения при IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000); // TODO :забить номера портов в настройки client = new TcpClient(localEndPoint); client.Connect(remoteEndPoint); networkStream = client.GetStream(); byte[] sendBytes = Encoding.UTF8.GetBytes(text); networkStream.Write(sendBytes, 0, sendBytes.Length); byte[] bytes = new byte[client.ReceiveBufferSize]; networkStream.Read(bytes, 0, client.ReceiveBufferSize); string returnData = Encoding.UTF8.GetString(bytes); //MessageBox.Show(returnData); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (networkStream != null) networkStream.Close(); if (client!=null) client.Close(); } } */ // реализаця с UDP internal static void SendMessage(string RemoteHost, string text) { UdpClient client = null; try { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000); // получатель сообщения при IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000); // TODO :забить номера портов в настройки client = new UdpClient(localEndPoint); byte[] sendBytes = Encoding.ASCII.GetBytes(text); networkStream.Write(sendBytes, 0, sendBytes.Length); byte[] bytes = new byte[client.ReceiveBufferSize]; networkStream.Read(bytes, 0, client.ReceiveBufferSize); string returnData = Encoding.UTF8.GetString(bytes); //MessageBox.Show(returnData); } catch (Exception e) { MessageBox.Show(e.Message); } finally { if (networkStream != null) networkStream.Close(); if (client != null) client.Close(); } }
// Use this for initialization void Start() { client = new System.Net.Sockets.UdpClient(); ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000); client.Connect(ep); InvokeRepeating("sendPos", 0.0f, 0.0167f); }
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); } } }
public void Send(byte[] datagram, int bytes, IPEndPoint ipEndPoint) { using (var udpClient = new UdpClient()) { udpClient.Send(datagram, bytes, ipEndPoint); } }
public static void Init(TestContext context) { Trace.Listeners.Add(new ConsoleTraceListener()); //Helper.Driver.Profile.DriverPath = "E:\\Workbench\\ZeroHub\\ZeroHub\\SharpNetUnitTest\\bin\\Debug\\Drivers\\"; //Helper.Driver.Uninstall(); //Helper.Driver.Install(); LocalIP = "10.3.0.1"; RemoteIPRange = "10.3.0.0"; // RemoteIPRange & Mask , and filter away local RemoteIP = "10.3.0.5"; Mask = "255.255.255.0"; net = new SharpNet(); net.Tap.SetMediaStatus(true); net.Tap.ConfigTun(LocalIP, RemoteIPRange, Mask); net.Tap.SetIpAddress(LocalIP, Mask, "10.3.0.0"); //net.Tap.ConfigDHCPMASQ("192.168.137.1", "255.255.255.255", "1.1.1.1", 2); Task.Delay(TimeSpan.FromSeconds(5)).Wait(); ping = new Ping(); localPort = 233; remotePort = 233; local = new IPEndPoint(IPAddress.Parse(LocalIP), localPort); remote = new IPEndPoint(IPAddress.Parse(RemoteIP), remotePort); //remote = new IPEndPoint(IPAddress.Any, remotePort); client = new System.Net.Sockets.UdpClient(local); }
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 async void ReceiveData(UdpReceiveResult result, UdpClient client) { try { System.Net.Sockets.UdpClient listener = client; byte[] data = result.Buffer; endpoint = result.RemoteEndPoint;
private bool Connect(string ip, int port) { try { if (port == 0 || ip == "") { return(false); } Debug.Log("connect battle udp-server " + ip + ":" + port); this.TryCloseSocket(); IPAddress ipAddress; AddressFamily af; bool ok = Misc.Utils.IPV4ToIPV6(ip, out ipAddress, out af); _server_endpoint = new IPEndPoint(ipAddress, port); _inner_socket = new UdpClient(); _inner_socket.Connect(_server_endpoint); _inner_socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1024 * 16); _inner_socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 1024 * 32); this.isConnected = true; } catch (Exception e) { this.isConnected = false; _inner_socket = null; Debug.Log(e.Message); return(false); } return(true); }
/// <summary> /// Connect to specific remote end point and only send and receive from that endpoint. /// </summary> /// <param name="endPoint"></param> public void Connect(IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { this.remoteEndPoint = remoteEndPoint; udp = new UdpClient(localEndPoint); receivingPending = true; udp.BeginReceive(new AsyncCallback(OnPacketReceived), this); }
// Connect for receiving messages public bool Connect(int localPort) { Disconnect(); receiveDone.Reset(); // Connect to a local port. try { localEP = new IPEndPoint(IPAddress.Any, localPort); // Create a UDP Client. clientReceive = new System.Net.Sockets.UdpClient(localEP); if (ConnectedStateChanged != null) ConnectedStateChanged(this, new ConnectedStateChangedEventArgs(true)); // Setup the receiver client thread receiverTask = new Thread(ReceiverLoop); receiverTask.Start(); // Signal that the connection has been made. connectDone.Set(); } catch (Exception e) { Disconnect(); // Console.WriteLine(e.ToString()); } return IsConnected; }
private bool startListen() { try { if (tcpListener == null) tcpListener = new TcpListener(IPAddress.Any, tcpPort); if (udpClient == null || udpClosed) { udpClient = new UdpClient(udpPort); //udpClient = new UdpClient(udpPort, AddressFamily.InterNetwork); udpClosed = false; } if (udpListenThread == null || !udpListenThread.IsAlive) { udpListenThread = new Thread(new ThreadStart(listenForUdpClients)); udpListenThread.IsBackground = true; udpListenThread.Start(); } if (tcpListenThread == null || !tcpListenThread.IsAlive) { tcpListenThread = new Thread(new ThreadStart(listenForTcpClients)); tcpListenThread.IsBackground = true; tcpListenThread.Start(); } Trace.WriteLine("Server started on TCP-Port: " + tcpPort + " and UDP-Port: " + udpPort); return true; } catch { Trace.WriteLine("Couldn't start server on Tcp-Port: " + tcpPort + " and Udp-Port: " + udpPort); return false; } }
/// <summary> /// Stops the UDP client. /// </summary> /// <param name="udpClient">The UDP client.</param> public static void StopUDPClient(UdpClient udpClient) { if (udpClient != null) { udpClient.Close(); } }
//データを受信した時 private void ReceiveCallback(IAsyncResult ar) { System.Net.Sockets.UdpClient udp = (System.Net.Sockets.UdpClient)ar.AsyncState; //非同期受信を終了する System.Net.IPEndPoint remoteEP = null; byte[] rcvBytes; try { rcvBytes = udp.EndReceive(ar, ref remoteEP); } catch (System.Net.Sockets.SocketException ex) { Console.WriteLine("受信エラー({0}/{1})", ex.Message, ex.ErrorCode); return; } catch (ObjectDisposedException ex) { //すでに閉じている時は終了 Console.WriteLine("Socketは閉じられています。"); return; } RecieveData(remoteEP.Address, remoteEP.Port, rcvBytes); //再びデータ受信を開始する udp.BeginReceive(ReceiveCallback, udp); }
//データを受信した時 private void ReceiveCallback(IAsyncResult ar) { System.Net.Sockets.UdpClient udp = (System.Net.Sockets.UdpClient)ar.AsyncState; //非同期受信を終了する System.Net.IPEndPoint remoteEP = null; byte[] rcvBytes; try { rcvBytes = udp.EndReceive(ar, ref remoteEP); } catch (System.Net.Sockets.SocketException ex) { Console.WriteLine("Error({0}/{1})", ex.Message, ex.ErrorCode); return; } catch (ObjectDisposedException ex) { //すでに閉じている時は終了 Console.WriteLine("Socket closed"); return; } //データを文字列に変換する string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes); var e = new UDP_ReceiveData(rcvMsg, remoteEP.Address.ToString()); Console.WriteLine("datarecived:{0}", rcvMsg); packet_receive(this, e); //再びデータ受信を開始する udp.BeginReceive(ReceiveCallback, udp); }
public WirelessMouse() { _mListener = new UdpClient(5051); _mEndPoint = new IPEndPoint(IPAddress.Any, 5051); Sensitivity = 10; }
/// <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) { } }
/// <summary> /// Default constructor for <code>UdpSocketClient.</code> /// </summary> public UdpSocketClient() { _backingUdpClient = new UdpClient { EnableBroadcast = true }; }
private static bool hostname_port_Validate(string hostname, int port) { bool no_error = true; try { // When hostname is not recognized as an ip address, // UdpClient take it as an hostname and // try to resolve it using network. // So it could take some times. // So I do not use it. // System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(hostname, port); // Parse accepts many things as ip address : // 127.0.0 127.0 127 6543 System.Net.IPAddress ipadd; no_error = System.Net.IPAddress.TryParse(hostname, out ipadd); if (no_error) { System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(hostname, port); } } catch (Exception) { no_error = false; } return(no_error); }
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]); } } }
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); } } }
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; } } }
// Start is called before the first frame update void Start() { //UdpClientオブジェクトを作成する udp = new System.Net.Sockets.UdpClient(); udp.EnableBroadcast = true; udp.Connect(new IPEndPoint(IPAddress.Broadcast, remotePort)); }
public SoundProxy(string branch, SipTransportBase sipProxy) { if (null == sipProxy) { throw new ArgumentNullException("settings"); } if (null == branch) { throw new ArgumentNullException("branch"); } if (0 == branch.Length) { throw new ArgumentException("Branch not specified."); } if (branch.Length > 250) { throw new ArgumentException("Branch is too long.", "branch"); } m_SipTransport = sipProxy; m_BranchAscii = SipTransportBase.g_Ascii.GetBytes(branch); m_udpClient = new System.Net.Sockets.UdpClient( new NET.IPEndPoint(m_SipTransport.LocalAddress, 0) ); m_udpReceiveThread = new System.Threading.Thread(UdpReceiveProc); m_udpReceiveThread.Start(); }
public ReliableUDPListener(UdpClient udp) { this.Udp = udp; this.RecieveThread = new Thread(ProcRecieve); this.RecieveThread.Start(); }
// Connect for receiving messages public bool Connect(int localPort) { Disconnect(); receiveDone.Reset(); // Connect to a local port. try { localEP = new IPEndPoint(IPAddress.Any, localPort); // Create a UDP Client. clientReceive = new System.Net.Sockets.UdpClient(localEP); if (ConnectedStateChanged != null) { ConnectedStateChanged(this, new ConnectedStateChangedEventArgs(true)); } // Setup the receiver client thread receiverTask = new Thread(ReceiverLoop); receiverTask.Start(); // Signal that the connection has been made. connectDone.Set(); } catch (Exception e) { Disconnect(); // Console.WriteLine(e.ToString()); } return(IsConnected); }
public void ReceiveCallback(System.IAsyncResult ar) { System.Net.Sockets.UdpClient u = (System.Net.Sockets.UdpClient)((UdpState)(ar.AsyncState)).u; System.Net.IPEndPoint e = (System.Net.IPEndPoint)((UdpState)(ar.AsyncState)).e; var receiveBytes = u.EndReceive(ar, ref e); Debug.Log(BitConverter.ToString(receiveBytes)); int pos = 16; // 16バイトから開始 int width = 0; for (int i = 0; i < 4; i++) { width = width * 256 + receiveBytes[pos++]; } int height = 0; for (int i = 0; i < 4; i++) { height = height * 256 + receiveBytes[pos++]; } ReceiveBytes = receiveBytes; H = height; W = width; received = true; }
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 GDISendingChannel(GDIDeviceContext dc) { fFormatter = new BinaryFormatter(); fMemoryStream = new MemoryStream(2048); fDeviceContext = dc; // Create the client fGDISpeaker = new UdpClient(); // Create the broadcast socket IPAddress ip = IPAddress.Parse(GDIPortal.Multicast_Pixtour_Group); fBroadcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); fBroadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip)); fBroadcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(GDIPortal.Multicast_Pixtour_Group), GDIPortal.Multicast_Pixtour_Port); fBroadcastSocket.Connect(ipep); // Setup the speaker fGraphPort = new GCDelegate(fDeviceContext.Resolution); fGraphPort.CommandPacked += new GCDelegate.DrawCommandProc(CommandPacked); // Setup the antennae to listen for commands fReceiver = new GDIReceivingChannel(GDIPortal.Multicast_Pixtour_Group, GDIPortal.Multicast_Pixtour_Port, fDeviceContext); }
public void Stop() { _IsStarted = false; SockThread.Join(); udpclient = null; }
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(); } }
public XPlaneData(string remoteHost, int remotePort = 49000, string localHost = "127.0.0.1", int localPort = 49010) { _remoteEP = new IPEndPoint(IPAddress.Parse(remoteHost), remotePort); _localEP = new IPEndPoint(IPAddress.Parse(localHost), localPort); _udpClient = new UdpClient(); _udpClient.Client.Bind(_localEP); }
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"); } }
private void Connect(IPEndPoint endPoint, int inputDeviceNumber, INetworkChatCodec codec) { waveIn = new WaveIn(); waveIn.BufferMilliseconds = 50; waveIn.DeviceNumber = inputDeviceNumber; waveIn.WaveFormat = codec.RecordFormat; waveIn.DataAvailable += waveIn_DataAvailable; waveIn.StartRecording(); udpSender = new UdpClient(); udpListener = new UdpClient(); // To allow us to talk to ourselves for test purposes: // http://stackoverflow.com/questions/687868/sending-and-receiving-udp-packets-between-two-programs-on-the-same-computer udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpListener.Client.Bind(endPoint); udpSender.Connect(endPoint); waveOut = new WaveOut(); waveProvider = new BufferedWaveProvider(codec.RecordFormat); waveOut.Init(waveProvider); waveOut.Play(); connected = true; var state = new ListenerThreadState { Codec = codec, EndPoint = endPoint }; ThreadPool.QueueUserWorkItem(ListenerThread, state); }
public UdpClientAdapter(UdpClient udpClient) { if (udpClient == null) throw new ArgumentNullException("udpClient"); _udpClient = udpClient; }
private void Find() { try { Cursor = Cursors.WaitCursor; byte[] dnsQuery; byte[] dnsReply; UdpClient dnsClient = new UdpClient(textBoxDnsServer.Text, 53); dnsQuery = MakeQuery(DateTime.Now.Millisecond * 60, textBoxDomain.Text); dnsClient.Send(dnsQuery, dnsQuery.Length); IPEndPoint ipEndPoint = null; dnsReply = dnsClient.Receive(ref ipEndPoint); richTextBoxMXServers.Text = MakeResponse(dnsReply, textBoxDomain.Text); } catch (SocketException ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor = Cursors.Default; } }
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 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); } }
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 UdpClient(SysClient sysClient, IPEndPoint endpoint) { this.sysClient = sysClient; this.endpoint = endpoint; listener = new UdpObservable(sysClient); instream = listener.SelectMany(SplitMessages); }
public ServerUDPTunnel(ServerPlayer player) { // enstablish an Connection this.player = player; udp = new UdpClient(new IPEndPoint(IPAddress.Any, Server.instance.UDPStartPort + (int)player.id)); udp.BeginReceive(onReceive, null); }
public IPhoneSensor(int port) { recievingUdpClient = new UdpClient(port); RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); calibrateGPS(34.1064,-117.7119); }
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 IObservable<UdpReceiveResult> CreateListener(IPAddress remoteAddress, int port) { if (remoteAddress == null) throw new ArgumentNullException(nameof(remoteAddress)); if (port < 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port), port, null); IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); var remoteIPBytes = remoteAddress.GetAddressBytes(); var localAddress = host.AddressList.FirstOrDefault(ip => ip.AddressFamily == remoteAddress.AddressFamily && ip.GetAddressBytes().Take(3).SequenceEqual(remoteIPBytes.Take(3))); if (localAddress == null) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Net_NoInterfaceInSameNetwork, remoteAddress, port)); var localEndPoint = new IPEndPoint(localAddress, port); var remoteEndPoint = new IPEndPoint(remoteAddress, port); return Observable.Using( () => { var client = new UdpClient { ExclusiveAddressUse = false }; client.Client.Bind(localEndPoint); client.Connect(remoteEndPoint.Address, 0); return client; }, client => Observable.While(() => client.Client.Connected, Observable.FromAsync(client.ReceiveAsync))); }
public void TestConnectAsync_Success() { var endPoint = new IPEndPoint( IPAddress.Loopback, 57319 ); var listener = new UdpClient( endPoint ); try { using ( var target = new UdpClientTransportManager( new RpcClientConfiguration() ) ) using ( var result = target.ConnectAsync( endPoint ) ) { Assert.That( result.Wait( TimeSpan.FromSeconds( 1 ) ) ); try { var transport = result.Result; Assert.That( transport.BoundSocket, Is.Not.Null ); Assert.That( ( transport as UdpClientTransport ).RemoteEndPoint, Is.EqualTo( endPoint ) ); } finally { result.Result.Dispose(); } } } finally { listener.Close(); } }
public UdpSocket(string Hostname, int Port, System.Action <byte[]> OnPacket, System.Action OnConnected, System.Action <string> OnCloseError) { // todo: put some "unhandled" debug in these if (OnPacket == null) { OnPacket = (Packet) => { } } ; if (OnCloseError == null) { OnCloseError = (Error) => { } } ; if (OnConnected == null) { OnConnected = () => { } } ; this.OnPacket = OnPacket; this.OnCloseError = OnCloseError; // if constructor doesn't throw, we're connected //EndPoint = GetEndPoint(Hostname, Port); //Socket = new UdpClient(EndPoint); EndPoint = new IPEndPoint(IPAddress.Any, 0); Socket = new UdpClient(Hostname, Port); OnConnected.Invoke(); StartRecv(); }
public UDPProtocol(int localPort) { this.localPort = localPort; udpClient = new System.Net.Sockets.UdpClient(localPort); udpClient.AllowNatTraversal(true); this.serverIPEndPoint = new IPEndPoint(IPAddress.Parse(serverIP), serverPort); }
/// <summary> /// Connect to any remote machine that wants to send to the given local port. /// </summary> public void Connect(IPEndPoint localEndPoint) { this.localEndPoint = localEndPoint; udp = new System.Net.Sockets.UdpClient(localEndPoint); udp.Client.ReceiveBufferSize = 1000000; receivingPending = true; udp.BeginReceive(new AsyncCallback(OnPacketReceived), this); }
private void InitClient() { _client = new System.Net.Sockets.UdpClient(11000); _client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12000)); //_receiveClient = new System.Net.Sockets.UdpClient(11000); receivingUdpClient = new System.Net.Sockets.UdpClient(12000); }
public void Close() { if (udp != null) { udp.Close(); udp = null; } }
public UdpClient(int localPort) { //_client = new System.Net.Sockets.UdpClient(new IPEndPoint(IPAddress.Any, 48899)) _client = new System.Net.Sockets.UdpClient(localPort); { //EnableBroadcast = true, //DontFragment = true, }; }
public UDPClient(Int32 port, bool ignoreUnknown) { this.ignoreUnknown = ignoreUnknown; this.rawClient = new System.Net.Sockets.UdpClient(port); this.output = new BlockingCollection <Packet>(); this.running = true; this.thread = new Thread(this.ListenThread); this.thread.Start(); }
private void CreateUdpClient() { _udpClient = new UdpClient(); uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; _ = _udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); }
/// <summary> /// 初始化 /// </summary> /// <param name="strLocalIP">本地IP</param> /// <param name="localPort">本地端口</param> /// <param name="remoteIP">服务器IP</param> /// <param name="remotePort">服务器端口</param> /// <param name="vModForm">接收数据修改显示事件</param> /// <param name="vServerOnLine">修改服务器在线或否的事件</param> public UdpClient(string strLocalIP, int localPort, string remoteIP, int remotePort, int vWorkStation, Action <IMsg> vModForm, Action <string, Color> vServerOnLine ) { if (Ins != null) { throw new Exception("对象已经存在"); } //g_m = em; //FrmMain frmMain = g_m as FrmMain; E_ModForm = vModForm; E_ServerOnLine = vServerOnLine; LocMsg = new MsgBase() { DaType = "BS", LocalIP = strLocalIP, LocalPort = localPort, RemoteIP = remoteIP, RemotePort = remotePort, WorkStation = vWorkStation }; Frame.Ins.FrmMsg = LocMsg; this.localPort = localPort; remoteEP = new IPEndPoint(IPAddress.Parse(remoteIP), remotePort); lock (this) { try { udpSend = new System.Net.Sockets.UdpClient(localPort); } catch (Exception ex) { throw ex; //MessageBox.Show("本地端口" + localPort.ToString() + "已被占用!", "提示", MessageBoxButtons.OK); //if (frmMain.IsHandleCreated) //{ // Environment.Exit(0); //} //return; } } udpSendState = new UdpState { ipEndPoint = remoteEP, udpClient = udpSend }; udpReceiveState = new UdpState { ipEndPoint = remoteEP, udpClient = udpSend }; readCallback = new AsyncCallback(SendCallback); receiveCallback = new AsyncCallback(ReceiveCallback); }
//打开socket通信 private void btnConnect_Click(object sender, EventArgs e) { System.Net.IPAddress ipaddr = null; if (!System.Net.IPAddress.TryParse(this.tbIP.Text, out ipaddr)) { MessageBox.Show("请正确填写IP地址!"); return; } int iPort = 0; if (!int.TryParse(this.tbPort.Text, out iPort) || iPort <= 0) { MessageBox.Show("请正确填写端口!"); return; } _ipaddrDes = new System.Net.IPEndPoint(ipaddr, iPort); if (_udp != null) { _udp.Close(); _udp = null; } _udp = new UdpClient(_portListen); try { _udp.Connect(_ipaddrDes); } catch (System.ObjectDisposedException) { MessageBox.Show("System.Net.Sockets.UdpClient 已关闭"); return; } catch (System.ArgumentOutOfRangeException) { MessageBox.Show("port 不在 System.Net.IPEndPoint.MinPort 和 System.Net.IPEndPoint.MaxPort 之间"); return; } catch (System.Net.Sockets.SocketException ex) { MessageBox.Show("试图访问套接字时发生错误:" + ex.Message); return; } catch (Exception ex) { MessageBox.Show("未知类型错误:" + ex.Message); return; } Program.SetAppSettingValue("DefaultIP", this.tbIP.Text); Program.SetAppSettingValue("DefaultPortNo", this.tbPort.Text); this.btnDisconnect.Enabled = true; this.btnConnect.Enabled = false; }
/// <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(); }
/// <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(); }
public UdpServer(int tcpPort, int updPort, string message) { _listenPort = updPort; _groupAddresses = new IPEndPoint(IPAddress.Any, _listenPort); _udpServer = new System.Net.Sockets.UdpClient(_listenPort); _tcpPort = tcpPort; _broadcastMessage = message; _mainLoop = new Thread(UdpListen); }
public async Task<IEnumerable<Server>> GetServers( MasterServerRegion region = MasterServerRegion.All, params MasterServerFilter[] masterServerFilters) { var servers = new List<Server>(); using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0))) { client.Connect(_steamSteamIpAddress, _steamSteamPort); string thisServer = null; while (thisServer != FIRST_AND_LAST_SERVER) { var requestPacket = CreateRequestPacket(thisServer ?? FIRST_AND_LAST_SERVER, region, masterServerFilters); await client.SendAsync(requestPacket, requestPacket.Length); var response = await client.ReceiveAsync(); var responseData = response.Buffer.ToList(); for (int i = HEADER_BYTES_LENGTH; i < responseData.Count; i++) { var ip = string.Join(".", responseData.GetRange(i, 4).ToArray()); int port = responseData[i + 4] << 8 | responseData[i + 5]; thisServer = string.Format("{0}:{1}", ip, port); if (thisServer != FIRST_AND_LAST_SERVER) { servers.Add(new Server(new IPEndPoint(IPAddress.Parse(ip), port))); } i += 5; } } } return servers; }
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(); }