import java.net.*; import java.io.*; class TestTcpNet { public static void main(String[] arg) { try { if (arg.length >= 2) { if (arg[0].equals("server")) { InetAddress addr = null; int port; if (arg.length >= 3) { addr = InetAddress.getByName(arg[1]); port = Integer.parseInt(arg[2]); } else { port = Integer.parseInt(arg[1]); } startServer(addr, port); } else if (arg[0].equals("client") && arg.length >= 3) { InetAddress addr = InetAddress.getByName(arg[1]); int port = Integer.parseInt(arg[2]); startClient(addr, port); } } } catch (Exception ex) { ex.printStackTrace(); } } private static void startServer(InetAddress addr, int port) throws IOException { ServerSocket servSock = new ServerSocket(port, 5, addr); // ServerScoket servSock = new ServerSocket(); // servSock.bind(new InetSocketAddress(addr, port)); System.out.println("Server has been started"); while (servSock.isBound()) { final Socket clientSock = servSock.accept(); new Thread() { public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); PrintWriter out = new PrintWriter(clientSock.getOutputStream(), true /*auto flushing*/); while (!clientSock.isClosed() && clientSock.isConnected()) { String s = in.readLine(); System.out.println("Client> " + s); if (s.toLowerCase().equals("hello")) { out.println("Server: 123"); } else if (s.toLowerCase().equals("quit")) { out.println("Bye!"); clientSock.close(); } else { out.println("Nothing to say"); } } } catch (Exception ex) { ex.printStackTrace(); } } }.start(); } } private static void startClient(InetAddress addr, int port) throws IOException { Socket sock = new Socket(addr, port); // Socket sock = new Socket(); // sock.connect(new InetSocketAddress(addr, port)); BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream())); PrintWriter out = new PrintWriter(sock.getOutputStream(), true /*auto flushing*/); BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in)); while (!sock.isClosed() && sock.isConnected()) { String s = systemIn.readLine(); out.println(s); s = in.readLine(); System.out.println(s); } } }