private MIDIPort(int port) { this.port = port; try { selector = Selector.Open(); channel = DatagramChannel.Open(); outboundQueue = new Queue <DatagramPacket>(); // inboundQueue = new ConcurrentLinkedQueue<DatagramPacket>(); InetSocketAddress address = new InetSocketAddress(this.port); channel.Socket().ReuseAddress = true; channel.ConfigureBlocking(false); channel.Socket().Bind(address); channel.Register(selector, Operations.Read | Operations.Write, new UDPBuffer()); Thread newThread = new Thread(new ThreadStart(Run)); newThread.Start(); } catch (IOException e) { e.StackTrace.ToString(); } }
public void Run() { Log.Info(TAG, "Started"); try { Thread currentThread = Thread.CurrentThread(); while (true) { Packet currentPacket; // TODO: Block when not connected do { currentPacket = (Packet)inputQueue.Poll(); if (currentPacket != null) { break; } Thread.Sleep(10); } while (!currentThread.IsInterrupted); if (currentThread.IsInterrupted) { break; } InetAddress destinationAddress = currentPacket.ip4Header.destinationAddress; int destinationPort = currentPacket.udpHeader.destinationPort; int sourcePort = currentPacket.udpHeader.sourcePort; Java.Lang.String ipAndPort = new Java.Lang.String(destinationAddress.HostAddress + ":" + destinationPort + ":" + sourcePort); System.Console.WriteLine("UDP Out: " + ipAndPort); DatagramChannel outputChannel = (DatagramChannel)channelCache.Get(ipAndPort); if (outputChannel == null) { outputChannel = DatagramChannel.Open(); vpnService.Protect(outputChannel.Socket()); try { outputChannel.Connect(new InetSocketAddress(destinationAddress, destinationPort)); } catch (IOException e) { Log.Error(TAG, "Connection error: " + ipAndPort, e); closeChannel(outputChannel); ByteBufferPool.Release(currentPacket.backingBuffer); continue; } outputChannel.ConfigureBlocking(false); currentPacket.SwapSourceAndDestination(); selector.Wakeup(); outputChannel.Register(selector, SelectionKey.OpRead, currentPacket); channelCache.Put(ipAndPort, outputChannel); } try { ByteBuffer payloadBuffer = currentPacket.backingBuffer; while (payloadBuffer.HasRemaining) { outputChannel.Write(payloadBuffer); } } catch (IOException e) { Log.Error(TAG, "Network write error: " + ipAndPort, e); channelCache.Remove(ipAndPort); closeChannel(outputChannel); } ByteBufferPool.Release(currentPacket.backingBuffer); } } catch (InterruptedException e) { Log.Info(TAG, "Stopping"); } catch (IOException e) { Log.Info(TAG, e.ToString(), e); } finally { closeAll(); } }