List of usage examples for java.net ServerSocket accept
public Socket accept() throws IOException
From source file:gomokuserver.GomokuServer.java
/** * @param args the command line arguments * @throws java.lang.InterruptedException *//* w w w .j a v a 2 s . c om*/ public static void main(String[] args) throws InterruptedException { if (args.length != 1) { System.out.println("Run with listen portno as argument"); return; } int portno = Integer.parseInt(args[0]); ServerSocket sc; try { System.out.print("Creating socket bound to " + portno + " ... "); sc = new ServerSocket(portno); System.out.println("DONE"); } catch (IOException ex) { System.out.println(ex.getMessage()); return; } FrontOffice fo = new FrontOffice(); Lobby lb = new Lobby(); fo.setReferalLobby(lb); fo.start(); lb.start(); while (!interrupted()) { try { Socket playersocket = sc.accept(); playersocket.setKeepAlive(true); System.out.println("Received client from " + playersocket.getInetAddress()); fo.handle(playersocket); } catch (IOException ex) { Logger.getLogger(GomokuServer.class.getName()).log(Level.SEVERE, null, ex); } } fo.interrupt(); lb.interrupt(); fo.join(); lb.join(); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; boolean listening = true; try {// w w w .j a v a2 s. co m serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(-1); } while (listening) new KKMultiServerThread(serverSocket.accept()).start(); serverSocket.close(); }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {/*w w w .j a va2 s . c om*/ serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } 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; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:cacheservice.CacheServer.java
/** * @param args the command line arguments *///from w w w. jav a 2s. c o m public static void main(String[] args) { // COMUNICACIN CON EL CLIENTE ServerSocket serverSocket; Socket socketCliente; DataInputStream in; //Flujo de datos de entrada DataOutputStream out; //Flujo de datos de salida String mensaje; int laTengoenCache = 0; //COMUNICACIN CON EL INDEX ServerSocket serverSocketIndex; Socket socketIndex; DataOutputStream outIndex; ObjectInputStream inIndex; String mensajeIndex; try { serverSocket = new ServerSocket(4444); System.out.print("SERVIDOR CACHE ACTIVO a la espera de peticiones"); //MIENTRAS PERMANEZCA ACTIVO EL SERVIDOR CACHE ESPERAR? POR PETICIONES DE LOS CLIENTES while (true) { socketCliente = serverSocket.accept(); in = new DataInputStream(socketCliente.getInputStream()); //Entrada de los mensajes del cliente mensaje = in.readUTF(); //Leo el mensaje enviado por el cliente System.out.println("\nHe recibido del cliente: " + mensaje); //Muestro el mensaje recibido por el cliente //int particionBuscada = seleccionarParticion(mensaje, tamanoCache, numeroParticiones); //Busco la particin //double tamanoParticion = Math.ceil( (double)tamanoCache / (double)numeroParticiones); //Thread hilo = new Hilo(mensaje,particionBuscada,cache.GetTable(),(int) tamanoParticion); //hilo.start(); //RESPUESTA DEL SERVIDOR CACHE AL CLIENTE out = new DataOutputStream(socketCliente.getOutputStream()); String respuesta = "Respuesta para " + mensaje; if (laTengoenCache == 1) { out.writeUTF(respuesta); System.out.println("\nTengo la respuesta. He respondido al cliente: " + respuesta); } else { out.writeUTF("miss"); out.close(); in.close(); socketCliente.close(); System.out.println("\nNo tengo la respuesta."); //LEER RESPUESTA DEL SERVIDOR INDEX serverSocketIndex = new ServerSocket(6666); socketIndex = serverSocketIndex.accept(); inIndex = new ObjectInputStream(socketIndex.getInputStream()); JSONObject mensajeRecibidoIndex = (JSONObject) inIndex.readObject(); System.out.println("He recibido del SERVIDOR INDEX: " + mensajeRecibidoIndex); //outIndex.close(); inIndex.close(); socketIndex.close(); } } } catch (Exception e) { System.out.print(e.getMessage()); } }
From source file:org.apache.cassandra.stress.StressServer.java
public static void main(String[] args) throws Exception { ServerSocket serverSocket = null; CommandLineParser parser = new PosixParser(); InetAddress address = InetAddress.getByName("127.0.0.1"); try {/*w w w . j a va 2s . c om*/ CommandLine cmd = parser.parse(availableOptions, args); if (cmd.hasOption("h")) { address = InetAddress.getByName(cmd.getOptionValue("h")); } } catch (ParseException e) { System.err.printf("Usage: ./bin/stressd start|stop|status [-h <host>]"); System.exit(1); } try { serverSocket = new ServerSocket(2159, 0, address); } catch (IOException e) { System.err.printf("Could not listen on port: %s:2159.%n", address.getHostAddress()); System.exit(1); } for (;;) new StressThread(serverSocket.accept()).start(); }
From source file:WriteObjectsFromSocket.java
public static void main(String args[]) { Socket rs;//from ww w.j a va 2s. com ServerSocket s; int PortNumber = 2000; // Fixed port boolean acceptLoop = true; ReaderWriter readerwriter = null; System.out.println("WriteFileFromSocket Running"); // //////////////////////////////////////////////////////////////// // Open a socket on this server and listen for a connection // Look for data if we get here that is requests // //////////////////////////////////////////////////////////////// try { System.out.println("Waiting to accept connection"); s = new ServerSocket(PortNumber); } catch (Exception e) { System.out.println("Unable to open port" + PortNumber); return; } while (acceptLoop) { try { rs = s.accept(); // Accept connections } catch (Exception e) { System.out.println("Accept failed port" + PortNumber); return; } readerwriter = new ReaderWriter(rs); // Start a thread to read the input } }
From source file:paxos.GameServer.java
public static void main(String args[]) { Game myGame = new Game(); Socket socket = null;//from w w w . j a v a 2 s .c o m ServerSocket GameServer = null; System.out.println("Server Listening......"); try { GameServer = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); System.out.println("Server error"); } while (true) { try { socket = GameServer.accept(); String clientAddress = socket.getRemoteSocketAddress().toString(); int clientPort = socket.getPort(); System.out.println("Connection established. Client: " + clientAddress + "on port " + clientPort); ServerThread st = new ServerThread(socket, myGame); st.start(); } catch (Exception e) { e.printStackTrace(); System.out.println("Connection Error"); } } }
From source file:server.kartu.tik.ServerKartuTIK.java
public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); Date date = new Date(); String jamskrg = sdf.format(date); ServerSocket ss; int port = 8888; try {//ww w . j a v a 2s . co m ss = new ServerSocket(port); System.out.println("Server started | " + jamskrg); while (statusServer) { Socket socket = ss.accept(); new Thread(new Runnable() { @Override public void run() { try { handleSocket(socket); } catch (IOException ex) { Logger.getLogger(ServerKartuTIK.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); //Thread.sleep(1000); } } catch (IOException ex) { System.out.println("Server sudah dibuka."); } }
From source file:Server_socket.java
public static void main(String argv[]) throws Exception { int puerto = Integer.parseInt(argv[0]); //String username = argv[1]; //String password = argv[2]; String clientformat;/* www .j av a2 s. com*/ String clientdata; String clientresult; String clientresource; String url_login = "http://localhost:3000/users/sign_in"; ServerSocket welcomeSocket = new ServerSocket(puerto); /*HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_login); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713'))); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String ret = EntityUtils.tostring(response.getEntity()); System.out.println(ret); */ while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientformat = inFromClient.readLine(); System.out.println("FORMAT: " + clientformat); BufferedReader inFromClient1 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientdata = inFromClient1.readLine(); System.out.println("DATA: " + clientdata); BufferedReader inFromClient2 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresult = inFromClient2.readLine(); System.out.println("RESULT: " + clientresult); BufferedReader inFromClient3 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresource = inFromClient3.readLine(); System.out.println("RESOURCE: " + clientresource); System.out.println("no pasas de aqui"); String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat; System.out.println(url); try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String stb = sb.toString(); System.out.println("estas aqui"); String output = null; String jsonText = stb; output = jsonText.replace("[", "").replace("]", ""); JSONObject json = new JSONObject(output); System.out.println(json.toString()); System.out.println("llegaste al final"); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); outToClient.writeBytes(json.toString()); } connectionSocket.close(); } }
From source file:fm.last.irccat.IRCCat.java
public static void main(String[] args) throws Exception { try {/*from w w w . j av a 2s .c o m*/ if (args.length == 0) { System.out.println("first param should be config file"); System.exit(-1); } XMLConfiguration c = null; try { c = new XMLConfiguration(args[0]); } catch (ConfigurationException cex) { System.err.println("Configuration error, check config file"); cex.printStackTrace(); System.exit(1); } IRCCat bot = new IRCCat(c); // listen for stuff and send it to irc: ServerSocket serverSocket = null; InetAddress inet = null; try { if (bot.getCatIP() != null) inet = InetAddress.getByName(bot.getCatIP()); } catch (UnknownHostException ex) { System.out.println("Could not resolve config cat.ip, fix your config"); ex.printStackTrace(); System.exit(2); } try { serverSocket = new ServerSocket(bot.getCatPort(), 0, inet); } catch (IOException e) { System.err.println("Could not listen on port: " + bot.getCatPort()); System.exit(1); } System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort()); while (true) { try { Socket clientSocket = serverSocket.accept(); // System.out.println("Connection on catport from: " // + clientSocket.getInetAddress().toString()); CatHandler handler = new CatHandler(clientSocket, bot); handler.start(); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } }