public void stop() { Stopped = true; if (mSelector != null) { try { mSelector.Close(); mSelector = null; } catch (Java.IO.IOException ex) { Debug.Fail($"TcpProxyServer mSelector.close() catch an exception: {ex}"); } } if (mServerSocketChannel != null) { try { mServerSocketChannel.Close(); mServerSocketChannel = null; } catch (Java.IO.IOException ex) { if (AppDebug.isDebug) { ex.PrintStackTrace(); } Debug.Fail($"TcpProxyServer mServerSocketChannel.close() catch an exception: {ex}"); } } }
/// <summary> /// 启动服务 /// </summary> /// <returns></returns> public async Task <bool> RunServerAsync(string ip, int port) { server = new ServerSocketChannel(); server.Hander(new DataChannelHandler <TData>(this)) .Hander(new MsgPackDecode()) .Hander(new MsgPackEcode()); return(await server.BindAsync(port, ip)); }
public static SecureDataNodeStarter.SecureResources GetSecureResources(Configuration conf) { HttpConfig.Policy policy = DFSUtil.GetHttpPolicy(conf); bool isSecure = UserGroupInformation.IsSecurityEnabled(); // Obtain secure port for data streaming to datanode IPEndPoint streamingAddr = DataNode.GetStreamingAddr(conf); int socketWriteTimeout = conf.GetInt(DFSConfigKeys.DfsDatanodeSocketWriteTimeoutKey , HdfsServerConstants.WriteTimeout); Socket ss = (socketWriteTimeout > 0) ? ServerSocketChannel.Open().Socket() : new Socket(); ss.Bind(streamingAddr, 0); // Check that we got the port we need if (ss.GetLocalPort() != streamingAddr.Port) { throw new RuntimeException("Unable to bind on specified streaming port in secure " + "context. Needed " + streamingAddr.Port + ", got " + ss.GetLocalPort()); } if (!SecurityUtil.IsPrivilegedPort(ss.GetLocalPort()) && isSecure) { throw new RuntimeException("Cannot start secure datanode with unprivileged RPC ports" ); } System.Console.Error.WriteLine("Opened streaming server at " + streamingAddr); // Bind a port for the web server. The code intends to bind HTTP server to // privileged port only, as the client can authenticate the server using // certificates if they are communicating through SSL. ServerSocketChannel httpChannel; if (policy.IsHttpEnabled()) { httpChannel = ServerSocketChannel.Open(); IPEndPoint infoSocAddr = DataNode.GetInfoAddr(conf); httpChannel.Socket().Bind(infoSocAddr); IPEndPoint localAddr = (IPEndPoint)httpChannel.Socket().LocalEndPoint; if (localAddr.Port != infoSocAddr.Port) { throw new RuntimeException("Unable to bind on specified info port in secure " + "context. Needed " + streamingAddr.Port + ", got " + ss.GetLocalPort()); } System.Console.Error.WriteLine("Successfully obtained privileged resources (streaming port = " + ss + " ) (http listener port = " + localAddr.Port + ")"); if (localAddr.Port > 1023 && isSecure) { throw new RuntimeException("Cannot start secure datanode with unprivileged HTTP ports" ); } System.Console.Error.WriteLine("Opened info server at " + infoSocAddr); } else { httpChannel = null; } return(new SecureDataNodeStarter.SecureResources(ss, httpChannel)); }
public TcpProxyServer(int port, Context context) { mSelector = Selector.Open(); mServerSocketChannel = ServerSocketChannel.Open(); mServerSocketChannel.ConfigureBlocking(false); mServerSocketChannel.Socket().Bind(new InetSocketAddress(port)); mServerSocketChannel.Register(mSelector, Operations.Accept); this.port = (short)mServerSocketChannel.Socket().LocalPort; this.context = context; Debug.Write($"AsyncTcpServer listen on {mServerSocketChannel.Socket().InetAddress.ToString()}:{this.port & 0xFFFF} success.\n"); }
/// <summary> /// Close the socket that's listening for new connections and (if /// we're connected) the debugger data socket. /// </summary> /*lock*/ internal void close() { try { if (mListenChannel != null) { mListenChannel.close(); } mListenChannel = null; closeData(); } catch (IOException) { Log.w("ddms", "Failed to close listener " + this); } }
/// <summary> /// Tell the thread to stop. Called from UI thread. /// </summary> internal void quit() { lock (this) { mQuit = true; wakeup(); Log.d("ddms", "Waiting for Monitor thread"); try { thread.Join(); // since we're quitting, lets drop all the client and disconnect // the DebugSelectedPort lock (mClientList) { foreach (Client c in mClientList) { c.close(false); // notify broadcast(CLIENT_DISCONNECTED, c); } mClientList.Clear(); } if (mDebugSelectedChan != null) { mDebugSelectedChan.close(); mDebugSelectedChan.socket().Close(); mDebugSelectedChan = null; } mSelector.close(); } catch (ThreadInterruptedException ie) { Console.WriteLine(ie.ToString()); Console.Write(ie.StackTrace); } catch (IOException e) { // TODO Auto-generated catch block Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } mInstance = null; } }
/* * Accept a new connection from a debugger. If successful, register it with * the Selector. */ private void acceptNewDebugger(Debugger dbg, ServerSocketChannel acceptChan) { lock (mClientList) { SocketChannel chan; if (acceptChan == null) { chan = dbg.accept(); } else { chan = dbg.accept(acceptChan); } if (chan != null) { chan.socket().NoDelay = true; wakeup(); try { chan.register(mSelector, SelectionKey.OP_READ, dbg); } catch (IOException ioe) { // failed, drop the connection dbg.closeData(); throw ioe; } catch (Exception re) { // failed, drop the connection dbg.closeData(); throw re; } } else { Log.w("ddms", "ignoring duplicate debugger"); // new connection already closed } } }
/* * We have some activity on the "debug selected" port. Handle it. */ private void processDebugSelectedActivity(SelectionKey key) { Debug.Assert(key.acceptable); ServerSocketChannel acceptChan = (ServerSocketChannel)key.channel(); /* * Find the debugger associated with the currently-selected client. */ if (mSelectedClient != null) { Debugger dbg = mSelectedClient.debugger; if (dbg != null) { Log.d("ddms", "Accepting connection on 'debug selected' port"); try { acceptNewDebugger(dbg, acceptChan); } catch (IOException) { // client should be gone, keep going } return; } } Log.w("ddms", "Connection on 'debug selected' port, but none selected"); try { SocketChannel chan = acceptChan.accept(); chan.close(); } catch (IOException) { // not expected; client should be gone, keep going } catch (NotYetBoundException) { displayDebugSelectedBindError(mDebugSelectedPort); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldGivePortConflictErrorWithPortNumberInIt() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldGivePortConflictErrorWithPortNumberInIt() { // Given an occupied port int port = 16000; using (ServerSocketChannel ignore = ServerSocketChannel.open().bind(new InetSocketAddress("localhost", port))) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.helpers.ListenSocketAddress address = new org.neo4j.helpers.ListenSocketAddress("localhost", port); ListenSocketAddress address = new ListenSocketAddress("localhost", port); // Expect Exception.expect(typeof(PortBindException)); // When IDictionary <BoltConnector, NettyServer.ProtocolInitializer> initializersMap = genericMap(new BoltConnector("test"), ProtocolOnAddress(address)); (new NettyServer(new NamedThreadFactory("mythreads"), initializersMap, new ConnectorPortRegister(), NullLog.Instance)).start(); } }
/// <summary> /// Create a new Debugger object, configured to listen for connections /// on a specific port. /// </summary> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: Debugger(Client client, int listenPort) throws java.io.IOException internal Debugger(Client client, int listenPort) { mClient = client; mListenPort = listenPort; mListenChannel = ServerSocketChannel.open(); mListenChannel.configureBlocking(false); // required for Selector var addr = new DnsEndPoint("localhost", listenPort); //$NON-NLS-1$ mListenChannel.socket().ExclusiveAddressUse = false; // .reuseAddress = true; // enable SO_REUSEADDR mListenChannel.socket().Bind(addr); mReadBuffer = ByteBuffer.allocate(INITIAL_BUF_SIZE); mPreDataBuffer = ByteBuffer.allocate(PRE_DATA_BUF_SIZE); mConnState = ST_NOT_CONNECTED; Log.d("ddms", "Created: " + this.ToString()); }
/// <summary> /// Accept a new connection from the specified listen channel. This /// is so we can listen on a dedicated port for the "current" client, /// where "current" is constantly in flux. /// /// Must be synchronized with other uses of mChannel and mPreBuffer. /// /// Returns "null" if we're already talking to somebody. /// </summary> internal SocketChannel accept(ServerSocketChannel listenChan) { if (listenChan != null) { SocketChannel newChan; newChan = listenChan.accept(); if (mChannel != null) { Log.w("ddms", "debugger already talking to " + mClient + " on " + mListenPort); newChan.close(); return(null); } mChannel = newChan; mChannel.configureBlocking(false); // required for Selector mConnState = ST_AWAIT_SHAKE; return(mChannel); } return(null); }
static void Main(string[] args) { //ServerSocketChannel针对TCP服务端 ServerSocketChannel server = new ServerSocketChannel(); server.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 Task <bool> r = server.BindAsync(7777, "127.0.0.1"); //SocketChannel针对TCP客户端或者UDP SocketChannel client = new SocketChannel(); ISocketChannel channel = client.InitChannel <TCPSocketChannel>(); client.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 r = client.ConnectAsync("127.0.0.1", 7777); //UDP 服务端接收 SocketChannel udpServer = new SocketChannel(20); ISocketChannel udpChannel = udpServer.InitChannel <UDPSocketChannel>(); //必须先创建 udpServer.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 r = udpServer.BindAsync(7777, "127.0.0.1"); //udp客户端 SocketChannel udpclient = new SocketChannel(); ISocketChannel udpchannel = udpclient.InitChannel <TCPSocketChannel>(); udpclient.Hander(new MessageDecode()) //反序列化 .Hander(new MessageEcode()) //序列化 .Hander(new SimpleChannelRead()) //读取 .Option(SockOption.recBufSize, 100); //设置参数 r = udpclient.ConnectAsync("127.0.0.1", 7777); }
/// <summary> /// Opens (or reopens) the "debug selected" port and listen for connections. </summary> /// <returns> true if the port was opened successfully. </returns> /// <exception cref="IOException"> </exception> private bool reopenDebugSelectedPort() { Log.d("ddms", "reopen debug-selected port: " + mNewDebugSelectedPort); if (mDebugSelectedChan != null) { mDebugSelectedChan.close(); } mDebugSelectedChan = ServerSocketChannel.open(); mDebugSelectedChan.configureBlocking(false); // required for Selector var addr = new DnsEndPoint("localhost", mNewDebugSelectedPort); //$NON-NLS-1$ mDebugSelectedChan.socket().ExclusiveAddressUse = false; // enable SO_REUSEADDR try { mDebugSelectedChan.socket().Bind(addr); if (mSelectedClient != null) { mSelectedClient.update(Client.CHANGE_PORT); } mDebugSelectedChan.register(mSelector, SelectionKey.OP_ACCEPT, this); return(true); } catch (Exception) { displayDebugSelectedBindError(mNewDebugSelectedPort); // do not attempt to reopen it. mDebugSelectedChan = null; mNewDebugSelectedPort = -1; return(false); } }
public _ChannelFactory_130(ServerSocketChannel externalHttpChannel) { this.externalHttpChannel = externalHttpChannel; }
public SecureResources(Socket streamingSocket, ServerSocketChannel httpServerSocket ) { this.streamingSocket = streamingSocket; this.httpServerSocket = httpServerSocket; }
public _NioServerSocketChannel_133(ServerSocketChannel baseArg1) : base(baseArg1) { }
/// <exception cref="System.IO.IOException"/> public DatanodeHttpServer(Configuration conf, DataNode datanode, ServerSocketChannel externalHttpChannel) { this.conf = conf; Configuration confForInfoServer = new Configuration(conf); confForInfoServer.SetInt(HttpServer2.HttpMaxThreads, 10); HttpServer2.Builder builder = new HttpServer2.Builder().SetName("datanode").SetConf (confForInfoServer).SetACL(new AccessControlList(conf.Get(DFSConfigKeys.DfsAdmin , " "))).HostName(GetHostnameForSpnegoPrincipal(confForInfoServer)).AddEndpoint( URI.Create("http://localhost:0")).SetFindPort(true); this.infoServer = builder.Build(); this.infoServer.AddInternalServlet(null, "/streamFile/*", typeof(StreamFile)); this.infoServer.AddInternalServlet(null, "/getFileChecksum/*", typeof(FileChecksumServlets.GetServlet )); this.infoServer.SetAttribute("datanode", datanode); this.infoServer.SetAttribute(JspHelper.CurrentConf, conf); this.infoServer.AddServlet(null, "/blockScannerReport", typeof(BlockScanner.Servlet )); this.infoServer.Start(); IPEndPoint jettyAddr = infoServer.GetConnectorAddress(0); this.confForCreate = new Configuration(conf); confForCreate.Set(FsPermission.UmaskLabel, "000"); this.bossGroup = new NioEventLoopGroup(); this.workerGroup = new NioEventLoopGroup(); this.externalHttpChannel = externalHttpChannel; HttpConfig.Policy policy = DFSUtil.GetHttpPolicy(conf); if (policy.IsHttpEnabled()) { this.httpServer = new ServerBootstrap().Group(bossGroup, workerGroup).ChildHandler (new _ChannelInitializer_117(this, jettyAddr, conf)); if (externalHttpChannel == null) { httpServer.Channel(typeof(NioServerSocketChannel)); } else { httpServer.ChannelFactory(new _ChannelFactory_130(externalHttpChannel)); } } else { // The channel has been bounded externally via JSVC, // thus bind() becomes a no-op. this.httpServer = null; } if (policy.IsHttpsEnabled()) { this.sslFactory = new SSLFactory(SSLFactory.Mode.Server, conf); try { sslFactory.Init(); } catch (GeneralSecurityException e) { throw new IOException(e); } this.httpsServer = new ServerBootstrap().Group(bossGroup, workerGroup).Channel(typeof( NioServerSocketChannel)).ChildHandler(new _ChannelInitializer_155(this, jettyAddr , conf)); } else { this.httpsServer = null; this.sslFactory = null; } }
/// <summary>Create a non-secure TcpPeerServer.</summary> /// <param name="socketWriteTimeout">The Socket write timeout in ms.</param> /// <param name="bindAddr">The address to bind to.</param> /// <exception cref="System.IO.IOException"/> public TcpPeerServer(int socketWriteTimeout, IPEndPoint bindAddr) { this.serverSocket = (socketWriteTimeout > 0) ? ServerSocketChannel.Open().Socket( ) : new Socket(); Server.Bind(serverSocket, bindAddr, 0); }