//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void processRequest(java.net.MulticastSocket socket, String request, java.net.InetAddress address, int port) throws java.io.IOException internal virtual void processRequest(MulticastSocket socket, string request, InetAddress address, int port) { Console.WriteLine(string.Format("Received '{0}' from {1}:{2:D}", request, address, port)); Regex p = Pattern.compile("SEARCH +\\* +.*^ST: *" + deviceName + "$.*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Matcher m = p.matcher(request); if (m.find()) { StringBuilder response = new StringBuilder(); int netServerPortShift = Modules.sceNetAdhocModule.getRealPortFromServerPort(0); if (netServerPortShift == 0) { // Set a default server port shift if none has been set. netServerPortShift = 100; Modules.sceNetAdhocModule.NetServerPortShift = netServerPortShift; Modules.sceNetAdhocModule.NetClientPortShift = 0; } response.Append(string.Format("Location: {0}:{1:D}", LocalHostIP, netServerPortShift)); Console.WriteLine(string.Format("Sending response '{0}' to {1}:{2:D}", response, address, port)); DatagramPacket packet = new DatagramPacket(response.ToString().GetBytes(), response.Length, address, port); socket.send(packet); } }
/// <summary> /// 发送组播 /// </summary> /// <param name="message"></param> public void SendBroadcastMessage(string message) { try { var endPoint = new IPEndPoint(MulticastAddress, MulticastPort); var byteList = Encoding.UTF8.GetBytes(message); if (byteList.Length > MaxByteLength) { throw new ArgumentException($"传入 message 转换为 byte 数组长度太长,不能超过{MaxByteLength}字节") { Data = { { "message", message }, { "byteList", byteList } } }; } MulticastSocket.SendTo(byteList, endPoint); } catch (Exception e) { Console.WriteLine("\n" + e); } }
public override void run() { Console.WriteLine(string.Format("Starting AutoDetectJpcsp ListenerThread")); sbyte[] response = new sbyte[256]; while (!exit_Renamed) { try { InetAddress listenAddress = InetAddress.getByName(multicastIp); MulticastSocket socket = new MulticastSocket(discoveryPort); socket.joinGroup(listenAddress); while (!exit_Renamed) { DatagramPacket packet = new DatagramPacket(response, response.Length); socket.receive(packet); processRequest(socket, new string(packet.Data, packet.Offset, packet.Length), packet.Address, packet.Port); } socket.close(); } catch (IOException e) { Console.WriteLine("ListenerThread", e); exit(); } } }
public virtual void discover() { try { igd = new IGD(); ListenerThread listener = new ListenerThread(this, igd); listener.Daemon = true; listener.Name = "UPnP Discovery Listener"; listener.Start(); while (!listener.Ready) { Utilities.sleep(100); } foreach (string device in deviceList) { string discoveryRequest = string.Format("M-SEARCH * HTTP/1.1\r\nHOST: {0}:{1:D}\r\nST: {2}\r\nMAN: \"ssdp:discover\"\r\nMX: {3:D}\r\n\r\n", multicastIp, discoveryPort, device, discoveryTimeoutMillis / 1000); IEnumerator <NetworkInterface> networkInterfaces = NetworkInterface.NetworkInterfaces; while (networkInterfaces.MoveNext()) { NetworkInterface networkInterface = networkInterfaces.Current; if (networkInterface.Up && networkInterface.supportsMulticast()) { for (IEnumerator <InetAddress> addresses = networkInterface.InetAddresses; addresses.MoveNext();) { InetAddress address = addresses.Current; if (address is Inet4Address && !address.LoopbackAddress) { MulticastSocket socket = new MulticastSocket(new InetSocketAddress(address, discoverySearchPort)); InetSocketAddress socketAddress = new InetSocketAddress(multicastIp, discoveryPort); DatagramPacket packet = new DatagramPacket(discoveryRequest.GetBytes(), discoveryRequest.Length, socketAddress); socket.send(packet); socket.disconnect(); socket.close(); } } } } } for (int i = 0; i < discoveryTimeoutMillis / 10; i++) { if (listener.Done) { break; } Utilities.sleep(10, 0); } listener.Done = true; while (!listener.Ready) { Utilities.sleep(100); } } catch (IOException e) { Console.WriteLine("discover", e); } }
public virtual void TestShouldSetMulticastSocketTtl() { GangliaContext context = new GangliaContext(); ContextFactory factory = ContextFactory.GetFactory(); factory.SetAttribute("gangliaContext.multicast", "true"); factory.SetAttribute("gangliaContext.multicast.ttl", "10"); context.Init("gangliaContext", factory); MulticastSocket multicastSocket = (MulticastSocket)context.datagramSocket; Assert.Equal("Did not set TTL", multicastSocket.GetTimeToLive( ), 10); }
public virtual void TestShouldCreateMulticastSocket() { GangliaContext context = new GangliaContext(); ContextFactory factory = ContextFactory.GetFactory(); factory.SetAttribute("gangliaContext.multicast", "true"); context.Init("gangliaContext", factory); Assert.True("Did not create MulticastSocket", context.datagramSocket is MulticastSocket); MulticastSocket multicastSocket = (MulticastSocket)context.datagramSocket; Assert.Equal("Did not set default TTL", multicastSocket.GetTimeToLive (), 1); }
public SenderReport() { mTransport = RtpSocket.TRANSPORT_UDP; mTcpHeader = new byte[4] { 0, 0, 0, PACKET_LENGTH }; mTcpHeader[0] = Convert.ToByte('$'); /* Version(2) Padding(0) */ /* ^ ^ PT = 0 */ /* | | ^ */ /* | -------- | */ /* | |--------------------- */ /* | || */ /* | || */ mBuffer[0] = (byte)Integer.ParseInt("10000000", 2); /* Packet Type PT */ mBuffer[1] = (byte)200; /* Byte 2,3 -> Length */ setLong(PACKET_LENGTH / 4 - 1, 2, 4); /* Byte 4,5,6,7 -> SSRC */ /* Byte 8,9,10,11 -> NTP timestamp hb */ /* Byte 12,13,14,15 -> NTP timestamp lb */ /* Byte 16,17,18,19 -> RTP timestamp */ /* Byte 20,21,22,23 -> packet count */ /* Byte 24,25,26,27 -> octet count */ try { usock = new MulticastSocket(); } catch (IOException e) { // Very unlikely to happen. Means that all UDP ports are already being used throw new RuntimeException(e.Message.ToString()); } upack = new DatagramPacket(mBuffer, 1); // By default we sent one report every 3 secconde interval = 3000; }
private void ReceiveBroadcastMessages() { // 接收需要绑定 MulticastPort 端口 var bytes = new byte[MaxByteLength]; EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); try { while (!_disposedValue) { var length = MulticastSocket.ReceiveFrom(bytes, ref remoteEndPoint); OnReceivedMessage(Encoding.UTF8.GetString(bytes, 0, length)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
/** * This RTP socket implements a buffering mechanism relying on a FIFO of buffers and a Thread. * @throws IOException */ public RtpSocket() { mCacheSize = 0; mBufferCount = 300; // TODO: readjust that when the FIFO is full mBuffers = new byte[mBufferCount][]; mPackets = new DatagramPacket[mBufferCount]; mReport = new SenderReport(); mAverageBitrate = new AverageBitrate(); mTransport = TRANSPORT_UDP; mTcpHeader = new byte[] { (byte)'$', 0, 0, 0 }; resetFifo(); for (int i = 0; i < mBufferCount; i++) { mBuffers[i] = new byte[MTU]; mPackets[i] = new DatagramPacket(mBuffers[i], 1); /* Version(2) Padding(0) */ /* ^ ^ Extension(0) */ /* | | ^ */ /* | -------- | */ /* | |--------------------- */ /* | || -----------------------> Source Identifier(0) */ /* | || | */ mBuffers[i][0] = (byte)Integer.ParseInt("10000000", 2); /* Payload Type */ mBuffers[i][1] = (byte)96; /* Byte 2,3 -> Sequence Number */ /* Byte 4,5,6,7 -> Timestamp */ /* Byte 8,9,10,11 -> Sync Source Identifier */ } try { mSocket = new MulticastSocket(); } catch (Java.Lang.Exception e) { throw new Java.Lang.Exception(e.Message.ToString()); } }
/// <summary> /// 启动组播 /// </summary> public void StartMulticast() { try { // 如果首次绑定失败,那么将无法接收,但是可以发送 TryBindSocket(); // Define a MulticastOption object specifying the multicast group // address and the local IPAddress. // The multicast group address is the same as the address used by the server. // 有多个 IP 时,指定本机的 IP 地址,此时可以接收到具体的内容 var multicastOption = new MulticastOption(MulticastAddress, LocalIpAddress); MulticastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption); } catch (Exception e) { Console.WriteLine(e.ToString()); } Task.Run(ReceiveBroadcastMessages); }
public static void Main(string[] args) { System.Console.WriteLine(": " + typeof(object).FullName); /// http://www.daniweb.com/software-development/java/threads/424998/udp-client-server-in-java new Thread( delegate() { try { DatagramSocket socket = new DatagramSocket(); //construct a datagram socket and binds it to the available port and the localhos byte[] b = Encoding.UTF8.GetBytes("hi from jvm!"); //creates a variable b of type byte DatagramPacket dgram; dgram = new DatagramPacket((sbyte[])(object)b, b.Length, InetAddress.getByName("239.1.2.3"), 40404); //sends the packet details, length of the packet,destination address and the port number as parameters to the DatagramPacket //dgram.setData(b); System.Console.WriteLine( "Sending " + b.Length + " bytes to " + dgram.getAddress() + ":" + dgram.getPort()); //standard error output stream while (true) { System.Console.WriteLine("."); socket.send(dgram); //send the datagram packet from this port Thread.Sleep(1000); //cause the current executed thread to sleep for a certain number of miliseconds } } catch { System.Console.WriteLine("server error"); } } ) { Name = "server" }.Start(); new Thread( delegate() { try { byte[] b = new byte[011]; DatagramPacket dgram = new DatagramPacket((sbyte[])(object)b, b.Length); MulticastSocket socket = new MulticastSocket(40404); // must bind receive side socket.joinGroup(InetAddress.getByName("239.1.2.3")); while (true) { socket.receive(dgram); // blocks until a datagram is received System.Console.WriteLine("Received " + Encoding.UTF8.GetString((byte[])(object)dgram.getData()) + " bytes from " + dgram.getAddress()); dgram.setLength(b.Length); // must reset length field!s } } catch { System.Console.WriteLine("client error"); } } ) { Name = "client" }.Start(); CLRProgram.XML = new XElement("hello", "world"); CLRProgram.CLRMain( ); }
protected override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); var sv = new ScrollView(this); var b2 = new Button(this); { var ll = new LinearLayout(this); //ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); var b1 = new Button(this).AttachTo(ll); b1.WithText("LANBroadcastListener createMulticastLock"); var c = 0; b1.AtClick( v => { // server error { Message = , StackTrace = android.os.NetworkOnMainThreadException //at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) //at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:175) //at libcore.io.IoBridge.sendto(IoBridge.java:473) //at java.net.PlainDatagramSocketImpl.send(PlainDatagramSocketImpl.java:182) //at java.net.DatagramSocket.send(DatagramSocket.java:284) new Thread( delegate() { try { var socket = new DatagramSocket(); //construct a datagram socket and binds it to the available port and the localhos c++; var b = Encoding.UTF8.GetBytes(c + " hi from jvm!"); //creates a variable b of type byte var dgram = new DatagramPacket((sbyte[])(object)b, b.Length, InetAddress.getByName("239.1.2.3"), 40404); //sends the packet details, length of the packet,destination address and the port number as parameters to the DatagramPacket //dgram.setData(b); //System.Console.WriteLine( // "Sending " + b.Length + " bytes to " + dgram.getAddress() + ":" + dgram.getPort());//standard error output stream socket.send(dgram); //send the datagram packet from this port } catch (Exception ex) { System.Console.WriteLine("server error " + new { ex.Message, ex.StackTrace }); } } ) { Name = "sender" }.Start(); } ); b2.setText("The other button!"); ll.addView(b2); this.setContentView(sv); } // http://www.zzzxo.com/q/answers-android-device-not-receiving-multicast-package-13221736.html new Thread( delegate() { // http://stackoverflow.com/questions/12610415/multicast-receiver-malfunction // http://answers.unity3d.com/questions/250732/android-build-is-not-receiving-udp-broadcasts.html // Acquire multicast lock wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); multicastLock = wifi.createMulticastLock("multicastLock"); //multicastLock.setReferenceCounted(true); multicastLock.acquire(); System.Console.WriteLine("LANBroadcastListener ready..."); try { byte[] b = new byte[0x100]; // https://code.google.com/p/android/issues/detail?id=40003 var port = 40404; MulticastSocket socket = new MulticastSocket(port); // must bind receive side socket.setBroadcast(true); socket.setReuseAddress(true); socket.setTimeToLive(30); socket.setReceiveBufferSize(0x100); // https://code.google.com/p/android/issues/detail?id=40003 // http://stackoverflow.com/questions/6550618/multicast-support-on-android-in-hotspot-tethering-mode // http://www.massapi.com/class/java/net/InetSocketAddress.java.html // http://www.javadocexamples.com/java/net/MulticastSocket/joinGroup(SocketAddress%20mcastaddr,NetworkInterface%20netIf).html // http://grokbase.com/t/hadoop/common-issues/117jsjk8d7/jira-created-hadoop-7472-rpc-client-should-deal-with-the-ip-address-changes var group = InetAddress.getByName("239.1.2.3"); var groupSockAddr = new InetSocketAddress(group, port); // what lan interfaces do we have? socket.joinGroup(groupSockAddr, NetworkInterface.getByName("wlan0") ); System.Console.WriteLine("LANBroadcastListener joinGroup..."); while (true) { DatagramPacket dgram = new DatagramPacket((sbyte[])(object)b, b.Length); socket.receive(dgram); // blocks until a datagram is received var bytes = new MemoryStream((byte[])(object)dgram.getData(), 0, dgram.getLength()); var listen = Encoding.UTF8.GetString(bytes.ToArray()); System.Console.WriteLine("Received " + dgram.getLength() + " bytes from " + dgram.getAddress()); //dgram.setLength(b.Length); // must reset length field!s } } catch { System.Console.WriteLine("client error"); } } ) { Name = "client" }.Start(); }
public override void run() { MulticastSocket[] sockets = new MulticastSocket[100]; int numberSockets = 0; try { IEnumerator <NetworkInterface> networkInterfaces = NetworkInterface.NetworkInterfaces; while (networkInterfaces.MoveNext() && numberSockets < sockets.Length) { NetworkInterface networkInterface = networkInterfaces.Current; if (networkInterface.Up && networkInterface.supportsMulticast() && !networkInterface.Loopback) { //JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops: for (IEnumerator <InetAddress> addresses = networkInterface.InetAddresses; addresses.hasMoreElements() && numberSockets < sockets.Length;) { InetAddress address = addresses.Current; if (address is Inet4Address && !address.LoopbackAddress) { sockets[numberSockets] = new MulticastSocket(new InetSocketAddress(address, discoverySearchPort)); sockets[numberSockets].SoTimeout = 1; numberSockets++; } } } } } catch (SocketException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } catch (IOException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } ISet <string> processedUrls = new HashSet <string>(); ready = true; sbyte[] buffer = new sbyte[1536]; while (!Done) { for (int i = 0; i < numberSockets && !Done; i++) { try { DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.Length); sockets[i].receive(responsePacket); if (responsePacket.Length > 0) { string reply = new string(responsePacket.Data, responsePacket.Offset, responsePacket.Length); //if (log.DebugEnabled) { Console.WriteLine(string.Format("Discovery: {0}", reply)); } string location = null; Pattern pLocation = Pattern.compile("^location: *(\\S+)$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Matcher mLocation = pLocation.matcher(reply); if (mLocation.find()) { location = mLocation.group(1); } string st = null; Pattern pSt = Pattern.compile("^st: *(\\S+)$", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); Matcher mSt = pSt.matcher(reply); if (mSt.find()) { st = mSt.group(1); } if (!string.ReferenceEquals(location, null) && !string.ReferenceEquals(st, null)) { //if (log.DebugEnabled) { Console.WriteLine(string.Format("Location: '{0}', st: '{1}'", location, st)); } if (!processedUrls.Contains(location)) { igd.discover(location); processedUrls.Add(location); if (igd.Valid && igd.isConnected(upnp)) { //if (log.DebugEnabled) { Console.WriteLine(string.Format("IGD connected with external IP: {0}", igd.getExternalIPAddress(upnp))); } Done = true; } } } else { Console.WriteLine(string.Format("Could not parse discovery response: {0}", reply)); } } } catch (SocketTimeoutException) { } catch (IOException) { } } } for (int i = 0; i < numberSockets; i++) { sockets[i].disconnect(); sockets[i].close(); } ready = true; }