Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

In this page you can find the example usage for java.net ServerSocket ServerSocket.

Prototype

public ServerSocket(int port) throws IOException 

Source Link

Document

Creates a server socket, bound to the specified port.

Usage

From source file:delete_tcp.java

public static void main(String ar[]) throws IOException {
    ServerSocket ss = new ServerSocket(9999);

    Socket s = ss.accept();/*from   w  ww .j  a  va  2 s .  co  m*/

    DataInputStream in = new DataInputStream(s.getInputStream());
    DataOutputStream out = new DataOutputStream(s.getOutputStream());

    String id = in.readUTF();

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    EmployeeJDBCTemplate employeeJDBCTemplate = (EmployeeJDBCTemplate) context.getBean("employeeJDBCTemplate");

    System.out.println("Deleting Records...");

    employeeJDBCTemplate.delete(Integer.parseInt(id));

    out.writeUTF("Success");

    s.close();

}

From source file:gomokuserver.GomokuServer.java

/**
 * @param args the command line arguments
 * @throws java.lang.InterruptedException
 *///  ww w.  j  a va2 s  . co  m
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:cacheservice.CacheServer.java

/**
 * @param args the command line arguments
 *///from   ww w  .j  a  va 2 s  . c om
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:com.googlecode.lineblog.websocket.v2.WebSocketServer.java

public static void main(String[] args) {
    try {/*from w  w w  .  j a  v  a 2s . com*/
        ServerSocket ss = new ServerSocket(SERVER_PORT);
        log.info("Listen----" + SERVER_PORT + "----port!");
        new Console().start();
        while (true) {
            Socket sk = ss.accept();
            new TokenThread(sk).start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:BufferedSocketClient.java

public static void main(String args[]) throws Exception {
        int cTosPortNumber = 1777;
        String str;//from  ww  w  .j av a  2s .c  o m

        ServerSocket servSocket = new ServerSocket(cTosPortNumber);
        System.out.println("Waiting for a connection on " + cTosPortNumber);

        Socket fromClientSocket = servSocket.accept();
        PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);

        BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));

        while ((str = br.readLine()) != null) {
            System.out.println("The message: " + str);

            if (str.equals("bye")) {
                pw.println("bye");
                break;
            } else {
                str = "Server returns " + str;
                pw.println(str);
            }
        }
        pw.close();
        br.close();

        fromClientSocket.close();
    }

From source file:EchoServer.java

public static void main(String[] args) {
    try {//  ww w.j  a  va 2s . c o m
        // establish server socket
        ServerSocket s = new ServerSocket(8189);

        // wait for client connection
        Socket incoming = s.accept();
        try {
            InputStream inStream = incoming.getInputStream();
            OutputStream outStream = incoming.getOutputStream();

            Scanner in = new Scanner(inStream);
            PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

            out.println("Hello! Enter BYE to exit.");

            // echo client input
            boolean done = false;
            while (!done && in.hasNextLine()) {
                String line = in.nextLine();
                out.println("Echo: " + line);
                if (line.trim().equals("BYE"))
                    done = true;
            }
        } finally {
            incoming.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:HttpMirror.java

public static void main(String args[]) {
    try {//ww  w  .  j a  v  a2s . c  om
        // Get the port to listen on
        int port = Integer.parseInt(args[0]);
        // Create a ServerSocket to listen on that port.
        ServerSocket ss = new ServerSocket(port);
        // Now enter an infinite loop, waiting for & handling connections.
        for (;;) {
            // Wait for a client to connect. The method will block;
            // when it returns the socket will be connected to the client
            Socket client = ss.accept();

            // Get input and output streams to talk to the client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            // Start sending our reply, using the HTTP 1.1 protocol
            out.print("HTTP/1.1 200 \r\n"); // Version & status code
            out.print("Content-Type: text/plain\r\n"); // The type of data
            out.print("Connection: close\r\n"); // Will close stream
            out.print("\r\n"); // End of headers

            // Now, read the HTTP request from the client, and send it
            // right back to the client as part of the body of our
            // response. The client doesn't disconnect, so we never get
            // an EOF. It does sends an empty line at the end of the
            // headers, though. So when we see the empty line, we stop
            // reading. This means we don't mirror the contents of POST
            // requests, for example. Note that the readLine() method
            // works with Unix, Windows, and Mac line terminators.
            String line;
            while ((line = in.readLine()) != null) {
                if (line.length() == 0)
                    break;
                out.print(line + "\r\n");
            }

            // Close socket, breaking the connection to the client, and
            // closing the input and output streams
            out.close(); // Flush and close the output stream
            in.close(); // Close the input stream
            client.close(); // Close the socket itself
        } // Now loop again, waiting for the next connection
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java HttpMirror <port>");
    }
}

From source file:net.socket.bio.TimeServer.java

/**
 * @param args/*from w w  w  . j a v a 2s .c  o m*/
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    int port = 8089;
    if (args != null && args.length > 0) {

        try {
            port = Integer.valueOf(args[0]);
        } catch (NumberFormatException e) {
            // 
        }

    }
    ServerSocket server = null;
    try {
        server = new ServerSocket(port);
        System.out.println("The time server is start in port : " + port);
        Socket socket = null;
        while (true) {
            socket = server.accept();
            System.out.println("socket name" + socket);
            new Thread(new TimeServerHandler(socket)).start();
        }
    } finally {
        IOUtils.closeQuietly(server);
    }
}

From source file:ThreadedEchoServer.java

public static void main(String[] args) {
    try {//  w w w  .  ja  v a  2  s.  c  om
        int i = 1;
        ServerSocket s = new ServerSocket(8189);

        while (true) {
            Socket incoming = s.accept();
            System.out.println("Spawning " + i);
            Runnable r = new ThreadedEchoHandler(incoming);
            Thread t = new Thread(r);
            t.start();
            i++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.couragelabs.logging.LogAppenderTestFixture.java

/**
 * Use this method to test the appender. Run this first, then run
 * GlobalContextSocketAppender::main/*www.ja  v  a 2s  .c o m*/
 *
 * @param args Program arguments. None are needed.
 * @throws java.lang.Exception if things go wrong
 */
@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    ServerSocket serverSocket = new ServerSocket(PORT);

    System.out.println("Starting listen loop.");
    while (true) {
        try {
            final Socket clientSocket = serverSocket.accept();
            System.out.println("Received client connection.");
            new Thread() {
                @Override
                public void run() {
                    ObjectInputStream i = null;
                    try {
                        i = new ObjectInputStream(clientSocket.getInputStream());
                        while (true) {
                            Object received = i.readObject();
                            System.out.println(ToStringBuilder.reflectionToString(received,
                                    ToStringStyle.SHORT_PREFIX_STYLE));
                            Thread.sleep(1000);
                        }
                    } catch (EOFException e) {
                        System.out.println("Client closed connection.");
                    } catch (Throwable t) {
                        t.printStackTrace();
                    } finally {
                        if (i != null) {
                            try {
                                i.close();
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    }
                }
            }.start();
            Thread.sleep(1000);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        System.out.println("Next...");
    }

}