// start with the first available port in the range STARTPORT-ENDPORT private void start(int websterPort, InetAddress address) throws IOException { try { port = websterPort; // check if the port is not required by the JVM system property String s = System.getProperty("webster.port"); if (s != null && s.length() > 0) { port = new Integer(s); } ss = new ServerSocket(port, 0, address); } catch (IOException ioe) { if (startPort == endPort) { logger.log(Level.SEVERE, "Port bind server socket failure: " + endPort, ioe); System.exit(1); } else { System.err.println("Port bind server socket failure: " + port); throw ioe; } } port = ss.getLocalPort(); if (debug) System.out.println( "Webster serving on : " + ss.getInetAddress().getHostAddress() + ":" + port); if (logger.isLoggable(Level.INFO)) logger.info("Webster serving on: " + ss.getInetAddress().getHostAddress() + ":" + port); if (debug) System.out.println("Webster listening on port: " + port); if (logger.isLoggable(Level.FINE)) { logger.fine("Webster listening on port: " + port); } try { pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(maxThreads); if (debug) System.out.println( "Webster minThreads [" + minThreads + "], " + "maxThreads [" + maxThreads + "]"); if (logger.isLoggable(Level.FINE)) logger.fine( "Webster minThreads [" + minThreads + "], " + "maxThreads [" + maxThreads + "]"); } catch (Exception e) { logger.log(Level.SEVERE, "Could not create ThreadPool", e); throw new RuntimeException("Could not create Thread Pool"); } if (soTimeout > 0) { if (debug) System.out.println("Webster Socket SO_TIMEOUT set to [" + soTimeout + "] millis"); if (logger.isLoggable(Level.FINE)) logger.fine("Webster Socket SO_TIMEOUT set to [" + soTimeout + "] millis"); } /* Set system property */ System.setProperty(CODESERVER, "http://" + getAddress() + ":" + getPort()); if (logger.isLoggable(Level.FINE)) logger.fine("Webster isDaemon: " + isDaemon); Thread runner = new Thread(this, "Webster"); if (isDaemon) { runner.setDaemon(true); } runner.start(); }
private void onBind(ProxyMessage msg) throws IOException { ProxyMessage response = null; if (proxy == null) ss = new ServerSocket(0); else ss = new SocksServerSocket(proxy, msg.ip, msg.port); ss.setSoTimeout(acceptTimeout); log("Trying accept on " + ss.getInetAddress() + ":" + ss.getLocalPort()); if (msg.version == 5) response = new Socks5Message(CProxy.SOCKS_SUCCESS, ss.getInetAddress(), ss.getLocalPort()); else response = new Socks4Message(Socks4Message.REPLY_OK, ss.getInetAddress(), ss.getLocalPort()); response.write(out); mode = ACCEPT_MODE; pipe_thread1 = Thread.currentThread(); pipe_thread2 = new Thread(this); pipe_thread2.start(); // Make timeout infinit. sock.setSoTimeout(0); int eof = 0; try { while ((eof = in.read()) >= 0) { if (mode != ACCEPT_MODE) { if (mode != PIPE_MODE) return; // Accept failed remote_out.write(eof); break; } } } catch (EOFException eofe) { // System.out.println("EOF exception"); return; // Connection closed while we were trying to accept. } catch (InterruptedIOException iioe) { // Accept thread interrupted us. // System.out.println("Interrupted"); if (mode != PIPE_MODE) return; // If accept thread was not successfull return. } finally { // System.out.println("Finnaly!"); } if (eof < 0) // Connection closed while we were trying to accept; return; // Do not restore timeout, instead timeout is set on the // remote socket. It does not make any difference. pipe(in, remote_out); }
public static void main(String[] args) { if (args.length < 1) { System.out.println("Need port"); return; } int port = Integer.parseInt(args[0]); try { ServerSocket server = new ServerSocket(port); System.out.println( "Login on " + server.getInetAddress().toString() + ":" + server.getLocalPort() + ".\nExit with a single x"); Socket client = server.accept(); LineNumberReader in = new LineNumberReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); while (true) { String str = in.readLine(); System.out.println(str); if (str.equals("x") == true) { client.close(); server.close(); break; } out.println(str); out.flush(); } } catch (IOException ex) { } }
public static void startServer() { try { System.out.println("Starting server..."); serverSocket = new ServerSocket(7788); System.out.println("Server Started... Address: " + serverSocket.getInetAddress()); while (true) { socket = serverSocket.accept(); for (int i = 0; i < 10; i++) { if (user[i] == null) { System.out.println("User " + (i + 1) + " connected from " + socket.getInetAddress()); socket.setTcpNoDelay(false); out = new ObjectOutputStream(socket.getOutputStream()); in = new ObjectInputStream(socket.getInputStream()); out.writeInt(i); out.flush(); User theUser = new User(out, in, i); user[i] = theUser; Thread thread = new Thread(user[i]); thread.start(); break; } } } } catch (IOException e) { e.printStackTrace(); } }
public void run() { while (true) { try { System.out.println("Server name: " + serverSocket.getInetAddress().getHostName()); System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept(); System.out.println("Just connected to " + server.getRemoteSocketAddress()); ObjectInputStream objectIn = new ObjectInputStream(server.getInputStream()); try { Recipe rec = (Recipe) objectIn.readObject(); startHMI(rec, rec.getProductName()); // System.out.println("Object Received: width: "+rec.getWidth()+" height: // "+rec.getHeight()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF( "Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!"); server.close(); } catch (SocketTimeoutException s) { System.out.println("Socket timed out!"); break; } catch (IOException e) { e.printStackTrace(); break; } } }
/* * receive process sent from slaves via socket */ public void receiveProcess() throws IOException, ClassNotFoundException { ServerSocket listener = null; Socket socket; ObjectInputStream in = null; try { // 1. creating a server socket listener = new ServerSocket(getPort()); while (true) { // 2. wait for connection System.out.println("Master Waiting for Slave"); socket = listener.accept(); System.out.println("Connection received from " + listener.getInetAddress().getHostName()); // 3.read object from inputstream in = new ObjectInputStream(socket.getInputStream()); // String s = (String) in.readObject(); // System.out.println("Message Received from slave" + s); MigratableProcess process = (MigratableProcess) in.readObject(); processList.add(process); } } catch (IOException e) { e.printStackTrace(); } finally { // 4.close connection in.close(); listener.close(); } }
public InetSocketAddress getAddress() { if (serverSocket != null && serverSocket.isBound()) { return new InetSocketAddress(serverSocket.getInetAddress(), serverSocket.getLocalPort()); } return address; }
public void listenSocket() { try { server = new ServerSocket(4321, 1, new InetSocketAddress(0).getAddress()); System.out.println( "Server is listening on " + server.getInetAddress().getHostName() + ":" + 4321); } catch (IOException e) { System.out.println("Could not listen on port 4321"); System.exit(-1); } try { client = server.accept(); System.out.println("Client connected on port " + 4321); has_client = true; } catch (IOException e) { System.out.println("Accept failed: 4321"); System.exit(-1); } try { in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); } catch (IOException e) { System.out.println("Read failed"); System.exit(-1); } }
/** * Create a server with the specified port, listen backlog, and local IP address to bind to. The * localIP argument can be used on a multi-homed host for a ServerSocket that will only accept * connect requests to one of its addresses. If localIP is null, it will default accepting * connections on any/all local addresses. The port must be between 0 and 65535, inclusive. <br> * This methods blocks. */ public void start(final int port, final int backlog, final InetAddress localIP) { executor = Executors.newFixedThreadPool(poolSize); try { ss = new ServerSocket(port, backlog, localIP); final String address = ss.getInetAddress().getHostAddress(); final int localPort = ss.getLocalPort(); log.info("Starting SOCKS Proxy on: {}:{}", address, localPort); setProxyStatus(ProxyStatus.STARTED); while (true) { final Socket s = ss.accept(); final String hostName = s.getInetAddress().getHostName(); final int port2 = s.getPort(); log.info("Accepted from:{}:{}", hostName, port2); final DnsProxyServer ps = new DnsProxyServer(auth, s, dnsResolver); executor.submit(ps); } } catch (final IOException ioe) { log.error("Can't start proxy", ioe); setProxyStatus(ProxyStatus.ERROR); } finally { } }
private void writeHostAndPortToFile(File portFile) { String host = socket.getInetAddress().getHostName(); int port = socket.getLocalPort(); // The motivation for the Log.warn would be better satisfied by Bug 38. Log.warn("echo " + host + ":" + port + " > " + portFile); StringUtilities.writeFile(portFile, host + ":" + port + "\n"); }
public void setTitleToListen() { try { String serverString = serverSocket.getInetAddress().getLocalHost().toString(); String serverIP = serverString.split("/")[1]; editor.setTitle("Listening on: " + serverIP + ":" + serverport); } catch (UnknownHostException e) { e.printStackTrace(); } }
/** @tests java.net.ServerSocket#getInetAddress() */ public void test_getInetAddress() throws IOException { InetAddress addr = InetAddress.getLocalHost(); s = new ServerSocket(0, 10, addr); try { assertEquals("Returned incorrect InetAdrees", addr, s.getInetAddress()); } finally { s.close(); } }
/** * This method will create a tunnel of a type defined by the properties facade and will then bind * a local temporary port for a client app to use to communicate through the proxy tunnel. Returns * an address to the local server a client can talk to. * * @param token * @param serverProxyAddress * @param serverProxyPort * @return * @throws IOException */ public InetSocketAddress startConnector( RequestToken token, InetAddress serverProxyAddress, int serverProxyPort, int bufferSize, ConsumerProxyPropertiesFacade props, SocketClientManagerController controller) throws IOException { /* * Attempts to start up a connection with the desired server proxy. */ // Note that both client and server are closed when the thread completes log.debug( "Creating Client instance to connect to server proxy: " + serverProxyAddress + ":" + serverProxyPort); Client client = props.getClientInstance(serverProxyAddress, serverProxyPort, token); /* * Start up a socket server bound to the local proxy hostname and to a * port unique to this request. */ InetAddress localProxyAddress = props.getClientProxyAddress(); log.debug("Local client proxy address set as: " + localProxyAddress); InetSocketAddress connectorAddress = new InetSocketAddress(localProxyAddress, 0); log.debug("Starting server socket for client to access on port: " + connectorAddress.getPort()); // Note that both client and server are closed when the thread completes ServerSocket server = new ServerSocket(); server.bind(connectorAddress); log.debug("Creating Server bound: " + server.getInetAddress() + ": " + server.getLocalPort()); ClientConnector connector = new ClientConnector(server, client, bufferSize, controller); Thread conn = new Thread(connector); log.debug("Starting new Client Connector thread."); conn.start(); return new InetSocketAddress(server.getInetAddress(), server.getLocalPort()); }
public void shutdown() { synchronized (lock) { shutdownRequested = true; } /* Now close the ServerSocket */ try { new Socket(sock.getInetAddress(), sock.getLocalPort()).close(); } catch (IOException ex) { Ganymede.stackTrace(ex); } }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Server address - ") .append(serverSocket.getInetAddress().getHostAddress()) .append(":") .append(serverSocket.getLocalPort()); sb.append("\nRoot folder - ").append(Config.defaultFolder); sb.append("\nMax connections - ").append(Config.threadPoolSize); sb.append("\nFile part size - ").append(Config.partSize).append(" bytes").append("\n"); return sb.toString(); }
public void init() { serverSocket = createServerSocket(); if (logger.isDebugEnabled()) { logger.debug( "Created " + info + "socket listener on " + serverSocket.getInetAddress() + ":" + serverSocket.getLocalPort()); } }
public String getListeningAddress(final boolean resolveMultiIfcWithLocal) { String address = serverSocket.getInetAddress().getHostAddress().toString(); if (resolveMultiIfcWithLocal && address.equals("0.0.0.0")) try { address = InetAddress.getLocalHost().getHostAddress().toString(); } catch (UnknownHostException e) { try { address = OChannel.getLocalIpAddress(true); } catch (Exception ex) { } } return address + ":" + serverSocket.getLocalPort(); }
public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(9999); System.out.println(ss.getLocalSocketAddress()); System.out.println(ss.getInetAddress()); while (true) { Socket client = ss.accept(); String input = IOUtils.readAll(client.getInputStream()); String info = String.format("Hello server"); System.out.println(info); } }
public IIOPAddress getLocalAddress() { IIOPAddress addr = new IIOPAddress(serverSocket.getInetAddress().toString(), serverSocket.getLocalPort()); if (configuration != null) { try { addr.configure(configuration); } catch (ConfigurationException ce) { if (logger.isWarnEnabled()) { logger.warn("ConfigurationException", ce); } } } return addr; }
public static void main(String[] args) { String ipv4; try { System.out.println("Stablishing the server socket..."); ServerSocket srvSock = new ServerSocket(4201); System.out.println( "Server socket stablished to " + srvSock.getInetAddress().getHostName() + " at port number " + srvSock.getLocalPort() + ".\n"); try { Socket comSock = srvSock.accept(); System.out.println( "New connection stablished with " + comSock.getInetAddress().getHostName() + " (port " + comSock.getPort() + "), trying to communicate..."); // DO STUFF try { BufferedReader br = new BufferedReader(new InputStreamReader(comSock.getInputStream())); ipv4 = br.readLine(); br.close(); comSock.close(); srvSock.close(); Socket sock = new Socket(ipv4, 4202); BufferedReader br2 = new BufferedReader(new InputStreamReader(sock.getInputStream())); System.out.println(br2.readLine()); br2.close(); sock.close(); // System.out.println(ipv4); } catch (Exception e) { e.printStackTrace(); System.out.println("Connection failed. Try again later."); } } catch (Exception e) { e.printStackTrace(); System.out.println("Problem with client.\n"); } } catch (Exception e) { System.out.println("Failed to create server socket:"); e.printStackTrace(); } }
/** * Create a server with a specific id, which listens at the designated port. * * @param name Name of the agent * @param port Listen to this port for connection requests */ public Server(String name, int port) { Name = name; listenPort = port; idCount = 0; try { server = new ServerSocket(listenPort); start(); serverId = server.getInetAddress().getHostName() + "_" + port; Log.info("started server " + serverId + " name " + Name); clients = new Vector<Session>(); Valid = true; } catch (Exception e) { Log.severe(Name + e.toString()); // Valid will be false } }
/* * Returns the string representation of the address that this * listen key represents. */ public String address() { InetAddress address = ss.getInetAddress(); /* * If bound to the wildcard address then use current local * hostname. In the event that we don't know our own hostname * then assume that host supports IPv4 and return something to * represent the loopback address. */ if (address.isAnyLocalAddress()) { try { address = InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { byte[] loopback = {0x7f, 0x00, 0x00, 0x01}; try { address = InetAddress.getByAddress("127.0.0.1", loopback); } catch (UnknownHostException x) { throw new InternalError("unable to get local hostname"); } } } /* * Now decide if we return a hostname or IP address. Where possible * return a hostname but in the case that we are bound to an * address that isn't registered in the name service then we * return an address. */ String result; String hostname = address.getHostName(); String hostaddr = address.getHostAddress(); if (hostname.equals(hostaddr)) { if (address instanceof Inet6Address) { result = "[" + hostaddr + "]"; } else { result = hostaddr; } } else { result = hostname; } /* * Finally return "hostname:port", "ipv4-address:port" or * "[ipv6-address]:port". */ return result + ":" + ss.getLocalPort(); }
/** * init the Selector * * @param ctx * @throws java.io.IOException */ private final void initSelector(Context ctx) throws IOException { try { isShutDown.set(false); connectorInstanceHandler = new ConnectorInstanceHandler.ConcurrentQueueDelegateCIH( getConnectorInstanceHandlerDelegate()); // Create the socket listener selector = Utils.openSelector(); if (role != Role.CLIENT) { serverSocketChannel = ServerSocketChannel.open(); serverSocket = serverSocketChannel.socket(); if (receiveBufferSize > 0) { try { serverSocket.setReceiveBufferSize(receiveBufferSize); } catch (SocketException se) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "setReceiveBufferSize exception ", se); } catch (IllegalArgumentException iae) { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "setReceiveBufferSize exception ", iae); } } if (inet == null) { portRange.bind(serverSocket, ssBackLog); } else { portRange.bind(serverSocket, inet, ssBackLog); } serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); serverSocket.setSoTimeout(serverTimeout); // Ephemeral support port = serverSocket.getLocalPort(); inet = serverSocket.getInetAddress(); } ctx.getController().notifyReady(); } catch (SocketException ex) { throw new BindException(ex.getMessage() + ": " + port + "=" + this); } }
private HostAndPort startServerSocket() throws Exception { if (serverSocketAddress != null) { serverSocket = new ServerSocket(serverSocketAddress.getPort()); } else { for (int i = 40000; i < 40100; i++) { try { serverSocket = new ServerSocket(i); } catch (IOException e) { // try next port } } assertNotNull(serverSocket, "Failed to create server socket; no ports free in range!"); serverSocketAddress = HostAndPort.fromParts( serverSocket.getInetAddress().getHostAddress(), serverSocket.getLocalPort()); } return serverSocketAddress; }
public Server() { try { serverSocket = new ServerSocket(1210); // window.setText("Сервер запущен. Адрес: " + serverSocket.getInetAddress().toString()); System.out.println("Сервер запущен. Адрес: " + serverSocket.getInetAddress().toString()); while (true) { // System.out.println("eee"); klientSocket = serverSocket.accept(); // window.setText("Подключён клиент. Адрес: " + klientSocket.getInetAddress().toString()); System.out.println("Подключён клиент. Адрес: " + klientSocket.getInetAddress().toString()); ServerThread server = new ServerThread(klientSocket); server.run(); // запуск потока // window.setText(server.getPlane().toString()); } } catch (IOException e) { System.err.println(e); } }
/** * Create a server with the specified port, listen backlog, and local IP address to bind to. The * localIP argument can be used on a multi-homed host for a ServerSocket that will only accept * connect requests to one of its addresses. If localIP is null, it will default accepting * connections on any/all local addresses. The port must be between 0 and 65535, inclusive. <br> * This methods blocks. */ public void start(int port, int backlog, InetAddress localIP) { try { ss = new ServerSocket(port, backlog, localIP); log( "Starting SOCKS Proxy on:" + ss.getInetAddress().getHostAddress() + ":" + ss.getLocalPort()); while (true) { Socket s = ss.accept(); log("Accepted from:" + s.getInetAddress().getHostName() + ":" + s.getPort()); ProxyServer ps = new ProxyServer(auth, s); (new Thread(ps)).start(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { } }
/** * Constructor, makes a new server listening on specified port. * * @param port The port to listen on. */ public Server(int port) { clientcounter = 0; shutdown = false; try { serversock = new ServerSocket(port); } catch (IOException e) { System.out.println("Could not create server socket."); return; } /* Server socket open, make a vector to store active threads. */ serverthreads = new Vector<ServerThread>(0, 1); /* Output connection info for the server */ System.out.println( "Server IP address: " + serversock.getInetAddress().getHostAddress() + ", port " + port); /* listen on the socket for connections. */ listen(); }
public void run() { try { LOG.debug("Starting proxy listener for address = '" + bindAddr + "', port = " + port); ss = new ServerSocket(port, 5, bindAddr); LOG.debug( "Proxy is listening for requests on " + ss.getInetAddress() + " port " + ss.getLocalPort()); } catch (IOException ex) { LOG.error("Error while creating / binding the proxy's server socket", ex); throw new ServiceException("Startup / restart failed", ex); } try { while (true) { try { Socket s = ss.accept(); // FIXME - Use a bounded thread pool executor. new Thread(factory.createProcessor(config, mapper, s)).start(); } catch (InterruptedIOException ex) { // FIXME - Synchronously shut down the processor pool. LOG.info("Interrupted - we're done"); break; } catch (IOException ex) { if (Thread.currentThread().isInterrupted()) { LOG.info("Interrupted - we're done (2)"); break; } LOG.debug("IO error", ex); } catch (Throwable ex) { LOG.error("Unexpected exception - proxy listener exiting", ex); break; } } } finally { try { ss.close(); } catch (IOException ex) { LOG.debug("IO error while closing ServerSocket", ex); } } }
public static void main(String[] args) { try { serverPort = getServerPort(args); Server httpServer = new Server(); // Open a server socket to accept incoming request // 1. If you want to test the server locally serverSocket = new ServerSocket(serverPort, 1, InetAddress.getByName("localhost")); // 2. If you want to test the server over network // serverSocket = new ServerSocket(serverPort); serverIP = serverSocket.getInetAddress().getHostAddress(); // start the http server Thread serverThread = new Thread(httpServer); serverThread.start(); } catch (IOException e) { System.out.println("Fatal Server Error!!!!"); e.printStackTrace(); } }
/** The "listen" thread that accepts a connection to the server */ public void run() { Socket socket; // accept a connection try { System.out.println("Bank running, listening for connections on " + server.getInetAddress()); socket = server.accept(); System.out.println( Calendar.getInstance().getTime() + " - Accepted new connection from " + socket.getInetAddress()); handleUser(socket); socket.close(); } catch (IOException e) { System.out.println("Class Server died: " + e.getMessage()); e.printStackTrace(); return; } // create a new thread to accept the next connection newListener(); }