@Override public void run() { List<Socket> inProgress = new ArrayList<>(); ServerSocketFactory factory = ServerSocketFactory.getDefault(); try { ss = factory.createServerSocket(0); ss.setSoTimeout(5000); socketReadyLatch.countDown(); while (!interrupted()) { inProgress.add(ss.accept()); // eat socket } } catch (java.net.SocketTimeoutException expected) { } catch (Exception e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException ignored) { } for (Socket s : inProgress) { try { s.close(); } catch (IOException ignored) { } } } }
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 static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(10008); System.out.println("Enroll: 130050131071"); System.out.println("Connection Socket Created"); try { while (true) { System.out.println("Waiting for Connection"); new EchoServer2(serverSocket.accept()); } } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } } catch (IOException e) { System.err.println("Could not listen on port: 10008."); System.exit(1); } finally { try { serverSocket.close(); } catch (IOException e) { System.err.println("Could not close port: 10008."); System.exit(1); } } }
/** Listens for client requests until stopped. */ public void run() { try { while (listener != null) { try { Socket socket = serverSocket.accept(); if (!paranoid || checkSocket(socket)) { Runner runner = getRunner(); runner.handle(socket); // new Connection (socket); } else socket.close(); } catch (Exception ex) { System.err.println("Exception in XML-RPC listener loop (" + ex + ")."); } catch (Error err) { System.err.println("Error in XML-RPC listener loop (" + err + ")."); } } } catch (Exception exception) { System.err.println("Error accepting XML-RPC connections (" + exception + ")."); } finally { System.err.println("Closing XML-RPC server socket."); try { serverSocket.close(); serverSocket = null; } catch (IOException ignore) { } } }
public void run() throws IOException { ServerSocket server = new ServerSocket(this.portNumber); this.socket = server.accept(); this.socket.setTcpNoDelay(true); server.close(); DataInputStream in = new DataInputStream(this.socket.getInputStream()); final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream()); while (true) { final String className = in.readUTF(); Thread thread = new Thread() { public void run() { try { loadAndRun(className); out.writeBoolean(true); System.err.println(VerifyTests.class.getName()); System.out.println(VerifyTests.class.getName()); } catch (Throwable e) { e.printStackTrace(); try { System.err.println(VerifyTests.class.getName()); System.out.println(VerifyTests.class.getName()); out.writeBoolean(false); } catch (IOException e1) { // ignore } } } }; thread.start(); } }
@AfterClass public static void tearDownClass() { Logger.info( HttpClientUtilsTest.class, "============= [tearDownClass]global take time milliseconds: " + (System.currentTimeMillis() - g_beginTime)); if (httpServer != null) { httpServer.stop(0); } if (httpServer2 != null) { httpServer2.stop(0); } if (serverSocket != null && !serverSocket.isClosed()) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } for (Socket s : clientSockets) { try { if (!s.isClosed()) s.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** Create the serversocket and use its stream to receive serialized objects */ public static void main(String args[]) { ServerSocket ser = null; Socket soc = null; String str = null; Date d = null; try { ser = new ServerSocket(8020); /* * This will wait for a connection to be made to this socket. */ soc = ser.accept(); InputStream o = soc.getInputStream(); ObjectInput s = new ObjectInputStream(o); str = (String) s.readObject(); d = (Date) s.readObject(); s.close(); // print out what we just received System.out.println(str); System.out.println(d); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println("Error during serialization"); System.exit(1); } }
private void server() { new CountDown(60).start(); while (true) { try { Socket socket = serverSock.accept(); System.out.println("New Client:" + socket); if (readyState[6] == 1) { System.out.println("正在游戏中,无法加入"); continue; } for (i = 0; i <= 5; i++) { if (players[i].equals("虚位以待")) break; } if (i > 5) { System.out.println("房间已满,无法加入"); continue; } i++; ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream()); clients.addElement(remoteOut); ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream()); new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start(); } catch (IOException e) { System.out.println(e.getMessage() + ": Failed to connect to client."); try { serverSock.close(); } catch (IOException x) { System.out.println(e.getMessage() + ": Failed to close server socket."); } } } }
/** Creates the server. */ public static void main(String args[]) { client = null; ServerSocket server = null; try { System.out.print("\nCreating Server...\n"); // creates the server server = new ServerSocket(8008); System.out.print("Created\n"); // get the ip Address and the host name. InetAddress localAddr = InetAddress.getLocalHost(); System.out.println("IP address: " + localAddr.getHostAddress()); System.out.println("Hostname: " + localAddr.getHostName()); } catch (IOException e) { // sends a System.out.println("IO" + e); } // constantly checks for a new aocket trying to attach itself to the trhead while (true) { try { client = server.accept(); // create a new thread. FinalMultiThread thr = new FinalMultiThread(client); System.out.print(client.getInetAddress() + " : " + thr.getUserName() + "\n"); CliList.add(thr); current++; thr.start(); } catch (IOException e) { System.out.println(e); } } }
public static void main(String args[]) throws IOException { ServerSocket sSocket = new ServerSocket(sPort, 10); // Arguments Handling if (args.length != 1) { System.out.println("Must specify a file-path argument."); } else { String currentDir = System.getProperty("user.dir"); filePath = currentDir + "/src/srcFile/" + args[0]; filename = args[0]; } // Get list of chunks owned chunkOwned(); // Call FileSplitter FileSplitter fs = new FileSplitter(); fs.split(filePath); System.out.println("Waiting for connection"); while (true) { Socket connection = sSocket.accept(); System.out.println("Connection received from " + connection.getInetAddress().getHostName()); new Thread(new MultiThreadServer(connection)).start(); } }
/** * creates a server socket listening on port specified in the object constructor, and then * enters an infinite loop waiting for incoming socket connection requests representing a worker * process attempting to connect to this server, which it handles via the enclosing server's * <CODE>addNewWorkerConnection(s)</CODE> method. */ public void run() { try { ServerSocket ss = new ServerSocket(_port); System.out.println("Srv: Now Accepting Worker Connections"); while (true) { try { Socket s = ss.accept(); System.out.println("Srv: Incoming New Worker Connection to the Network"); System.out.println( "Srv: Thread may have to wait if an init_cmd has not yet arrived from the client"); addNewWorkerConnection(s); System.out.println("Srv: finished adding new worker connection to the _workers"); } catch (Exception e) { utils.Messenger.getInstance() .msg( "PDBTExecSingleCltWrkInitSrv.W2Thread.run(): " + "An error occured while adding new worker connection", 2); // e.printStackTrace(); } } } catch (IOException e) { // e.printStackTrace(); utils.Messenger.getInstance() .msg( "PDBTExecSingleCltWrkInitSrv.W2Thread.run(): " + "Failed to create Server Socket, Server exiting.", 0); System.exit(-1); } }
/** * creates a server socket listening on the port specified in the parameter of the constructor, * and waits for a single incoming client connection which it handles by invoking the <CODE> * addNewClientConnection(s)</CODE> method of the enclosing server, and then the thread exits. */ public void run() { try { ServerSocket ss = new ServerSocket(_port); System.out.println("Srv: Now Accepting Single Client Connection"); // while (true) { try { Socket s = ss.accept(); System.out.println("Srv: Client Added to the Network"); addNewClientConnection(s); System.out.println("Srv: finished adding client connection"); } catch (Exception e) { // e.printStackTrace(); System.err.println("Client Connection failed, exiting..."); System.exit(-1); } // } } catch (IOException e) { // e.printStackTrace(); utils.Messenger.getInstance() .msg( "PDBTExecSingleCltWrkInitSrv.C2Thread.run(): " + "Failed to create Server Socket, Server exiting.", 0); System.exit(-1); } }
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(PORT); } catch (IOException e) { System.err.println("Could not listen on port: " + PORT + "."); System.exit(1); } while (true) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); startTime = System.currentTimeMillis(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; while ((inputLine = in.readLine()) != null) { if (messageCount.get(clientSocket) == null) { messageCount.put(clientSocket, 1); } else { messageCount.put(clientSocket, messageCount.get(clientSocket) + 1); } overallMessageCount += 1; System.out.println("---------------------------------------"); System.out.println("Client: " + clientSocket.toString()); System.out.println( "aktive since " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds"); System.out.println(new Date(System.currentTimeMillis())); System.out.println("Overall Message Count: " + overallMessageCount); System.out.println("Message Count from Client: " + messageCount.get(clientSocket)); System.out.println("Message " + inputLine); System.out.println("---------------------------------------"); outputLine = inputLine.toUpperCase(); if (outputLine.equals("END")) { out.println("abort"); break; } out.println(outputLine); } out.close(); in.close(); clientSocket.close(); System.out.println("All Closed"); } // serverSocket.close(); }
public static void main(String args[]) throws Exception { int count = 0; ServerSocket serv = null; InputStream in = null; OutputStream out = null; Socket sock = null; int clientId = 0; Map<Integer, Integer> totals = new HashMap<Integer, Integer>(); try { serv = new ServerSocket(8888); } catch (Exception e) { e.printStackTrace(); } while (serv.isBound() && !serv.isClosed()) { System.out.println("Ready..."); try { sock = serv.accept(); in = sock.getInputStream(); out = sock.getOutputStream(); char c = (char) in.read(); System.out.print("Server received " + c); switch (c) { case 'r': clientId = in.read(); totals.put(clientId, 0); out.write(0); break; case 't': clientId = in.read(); int x = in.read(); System.out.print(" for client " + clientId + " " + x); Integer total = totals.get(clientId); if (total == null) { total = 0; } totals.put(clientId, total + x); out.write(totals.get(clientId)); break; default: int x2 = in.read(); int y = in.read(); System.out.print(" " + x2 + " " + y); out.write(x2 + y); } System.out.println(""); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) out.close(); if (in != null) in.close(); if (sock != null) sock.close(); } } }
public void startServer() throws IOException { serverSock = new ServerSocket(); serverSock.bind(new InetSocketAddress(ip, port)); System.out.println("You have connected"); while (true) { Socket socket = serverSock.accept(); // Remember that .accept is a blocking call. handleClient(socket); } }
/** launches the administration of the switch */ private void runAdmin() { try { final ServerSocket ss = new ServerSocket(admin_port); while ( /*!this.stop &&*/ !Main.stop) { // Idealement, il faurait gerer un pool de threads Socket s = ss.accept(); new Thread(new AdminSwitch(this, s)).start(); } } catch (IOException e) { System.err.println("pb de connection admin switch"); } }
/** Starts the server. */ public void start() { System.out.println("JavaChat server started on port " + PORT_NUMBER + "!"); try { ServerSocket s = new ServerSocket(PORT_NUMBER); for (; ; ) { Socket incoming = s.accept(); new ClientHandler(incoming).start(); } } catch (Exception e) { e.printStackTrace(); } System.out.println("JavaChat server stopped."); }
public void launch() { try { ss = new ServerSocket(8888); started = true; System.out.println("server is start!"); while (started) { s = ss.accept(); VClient vc = new VClient(s); clients.add(vc); new Thread(vc).start(); } ss.close(); } catch (IOException e) { e.printStackTrace(); } }
public SetIfModifiedSince() throws Exception { serverSock = new ServerSocket(0); int port = serverSock.getLocalPort(); Thread thr = new Thread(this); thr.start(); Date date = new Date(new Date().getTime() - 1440000); // this time yesterday URL url; HttpURLConnection con; // url = new URL(args[0]); url = new URL("http://localhost:" + String.valueOf(port) + "/anything"); con = (HttpURLConnection) url.openConnection(); con.setIfModifiedSince(date.getTime()); con.connect(); int ret = con.getResponseCode(); if (ret == 304) { System.out.println("Success!"); } else { throw new RuntimeException( "Test failed! Http return code using setIfModified method is:" + ret + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method"); } }
/** * Closes the server socket and the connections with all clients. Any exception thrown while * closing a client is ignored. If one wishes to catch these exceptions, then clients should be * individually closed before calling this method. The method also stops listening if this thread * is running. If the server is already closed, this call has no effect. * * @exception IOException if an I/O error occurs while closing the server socket. */ public final void close() throws IOException { if (serverSocket == null) return; stopListening(); try { serverSocket.close(); } finally { synchronized (this) { // Close the client sockets of the already connected clients Thread[] clientThreadList = getClientConnections(); for (int i = 0; i < clientThreadList.length; i++) { try { ((ConnectionToClient) clientThreadList[i]).close(); } // Ignore all exceptions when closing clients. catch (Exception ex) { } } serverSocket = null; } try { connectionListener.join(); // Wait for the end of listening thread. } catch (InterruptedException ex) { } catch (NullPointerException ex) { } // When thread already dead. serverClosed(); } }
public void startServer() throws Exception { while (true) { Socket s = server.accept(); cClient.add(new ClientConn(s)); ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort()); ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n"); } }
public void run() { try { SocketChannel sc = SocketChannel.open(); InetSocketAddress sinaAddr = new InetSocketAddress("sina.com", 80); sc.socket().connect(sinaAddr); // init a selector via helper class selector provider Selector aSel = SelectorProvider.provider().openSelector(); Socket soc = new Socket("host", 80); soc.getChannel().register(aSel, SelectionKey.OP_ACCEPT); // init a channel for server socket. method 1 ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(true); // method 2, get server socket first, then init its channel ServerSocket ss = new ServerSocket(); ServerSocketChannel ssc2 = ss.getChannel(); // set socket channel as non blocking. ssc.configureBlocking(false); InetSocketAddress isa = new InetSocketAddress("localhost", 9999); ssc.socket().bind(isa); SelectionKey acceptKey = ssc.register(aSel, SelectionKey.OP_ACCEPT); int keysAdded = 0; while ((keysAdded = aSel.select()) > 0) { Set readyKeys = aSel.selectedKeys(); Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); ServerSocketChannel n = (ServerSocketChannel) sk.channel(); // now we got a new socket and its channel after accept in server Socket s = n.accept().socket(); SocketChannel socketChannel = s.getChannel(); socketChannel.register(aSel, SelectionKey.OP_READ); } } } catch (Exception e) { } }
private void acceptConnections() { for (; ; ) { try { String handlerName = fullName + "-Handler-" + Thread.activeCount(); new Thread(new ClientHandler(socket.accept()), handlerName).start(); } catch (Exception ex) { Log.warn(fullName + ": exception accepting connection.", ex); } } }
public void shutdown() { try { running = false; for (WorkerThread t : threads) { t.stopThread(); } serverSocket.close(); } catch (Exception ignore) { } }
public void run() { try { while (true) { Socket nsk; try { nsk = sk.accept(); } catch (IOException e) { break; } new Client(nsk); } } finally { try { sk.close(); } catch (IOException e) { throw (new RuntimeException(e)); } } }
public void listen(EndPoint localEp, boolean isHttp) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); ServerSocket ss = serverChannel.socket(); ss.bind(localEp.getInetAddress()); serverChannel.configureBlocking(false); SelectionKeyHandler handler = null; if (isHttp) { handler = new HttpConnectionHandler(); } else { handler = new TcpConnectionHandler(localEp); } SelectionKey key = SelectorManager.getSelectorManager() .register(serverChannel, handler, SelectionKey.OP_ACCEPT); endPoints_.add(localEp); listenSockets_.put(localEp, key); }
public void run() { boolean status; sf.DEBUG("Listen server running."); // open up our server socket try { m_serverSocket = new ServerSocket(m_nPort); } catch (IOException e) { sf.VERBOSE("Could not listen on port: " + m_nPort); if (sf.cntrlWndw != null) { sf.cntrlWndw.ClearListenServer(); } return; } sf.VERBOSE("Listening for client connections on port " + m_nPort); // if (SerialForward.bSourceSim) // { SetDataSource(); sf.InitSerialPortIO(); // } // start listening for connections try { ClientServicer rcv; Socket currentSocket; while (!m_bShutdown) { currentSocket = m_serverSocket.accept(); ClientServicer newServicer = new ClientServicer(currentSocket, sf, this); newServicer.start(); vctServicers.add(newServicer); } m_serverSocket.close(); } catch (IOException e) { /*try { this.sleep(500); } catch (Exception e2) { }*/ sf.VERBOSE("Server Socket closed"); } finally { ShutdownAllClientServicers(); if (sf.serialPortIO != null) sf.serialPortIO.Shutdown(); sf.VERBOSE("--------------------------"); if (sf.cntrlWndw != null) { sf.cntrlWndw.ClearListenServer(); } } }
@Override public void run() { isActive = true; try { serverSocket = new ServerSocket(Utils.getLOCAL_PORT()); notifyStatusListeners( Messages.getInstance() .getString( "T_NET_SERVER_LISTENING_ON_PORT", Integer.toString(Utils.getLOCAL_PORT()))); // $NON-NLS-1$ } catch (IOException e) { if (e instanceof BindException) { notifyStatusListeners( Messages.getInstance() .getString( "T_PORT_ALREADY_IN_USE", Integer.toString(Utils.getLOCAL_PORT()))); // $NON-NLS-1$ } else e.printStackTrace(); isActive = false; } while (isActive) { try { listenSocket = serverSocket.accept(); ois = new ObjectInputStream(listenSocket.getInputStream()); oos = new ObjectOutputStream(listenSocket.getOutputStream()); receivedMessage = ois.readInt(); System.out.println(messageToString(receivedMessage)); switch (receivedMessage) { case CONNECT: handleConnect(); break; case SEND_CODE: handleSendCode(); break; case KEEP_ALIVE: handleKeepAlive(); break; case DISCONNECT: handleDisconnect(); break; } ois.close(); oos.close(); } catch (IOException e) { System.out.println(e.getMessage()); } finally { if (listenSocket != null) try { listenSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public void start() { keepGoing = true; /* create socket server and wait for connection requests */ try { // the socket used by the server ServerSocket serverSocket = new ServerSocket(port); // infinite loop to wait for connections while (keepGoing) { // format message saying we are waiting display("Server menunggu koneksi Client pada port " + port + "."); Socket socket = serverSocket.accept(); // accept connection // if I was asked to stop if (!keepGoing) break; ClientThread t = new ClientThread(socket); // make a thread of it al.add(t); // save it in the ArrayList t.start(); } // I was asked to stop try { serverSocket.close(); for (int i = 0; i < al.size(); ++i) { ClientThread tc = al.get(i); try { tc.sInput.close(); tc.sOutput.close(); tc.socket.close(); } catch (IOException ioE) { // not much I can do } } } catch (Exception e) { display("Exception closing the server and clients: " + e); } } // something went bad catch (IOException e) { String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n"; display(msg); } }
public void run() { while (true) { try { System.out.println( "TCP Server waiting for client on port " + serverSocket.getLocalPort() + "..."); Socket server = serverSocket.accept(); System.out.println("Just received request from " + server.getRemoteSocketAddress()); /* parsing a request from socket */ DataInputStream in = new DataInputStream(server.getInputStream()); String request = in.readUTF(); System.out.println("Request: " + request); /* handle the request */ String output = null; output = requestHandler(request); System.out.print(output); /* display dataTable */ System.out.print("-dataTable--------\n"); Enumeration<String> key = dataTable.keys(); while (key.hasMoreElements()) { String str = key.nextElement(); System.out.println(str + ": " + dataTable.get(str)); } System.out.print("------------------\n"); /* send the result back to the client */ DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF(output); server.close(); } catch (SocketTimeoutException s) { System.out.println("Socket timed out!"); break; } catch (IOException e) { e.printStackTrace(); break; } } }