Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is an "echo server" example</p> <pre><code>import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws IOException { ServerSocket serverSocket = null; DataInputStream serverInput = null; PrintStream serverOutput = null; String line = null; Socket clientSocket = null; // create server socket try { serverSocket = new ServerSocket(2012); clientSocket = serverSocket.accept(); serverInput = new DataInputStream(clientSocket.getInputStream()); serverOutput = new PrintStream(clientSocket.getOutputStream()); } catch(IOException e){System.out.println(e);} // receive data and send it back to the client try { while(true) { line = serverInput.readLine(); if(line.equals("exit")) { break; } else { if(!line.equals(null) &amp;&amp; !line.equals("exit")) { System.out.println("Received " +line); line = line+" MODIFIED"; serverOutput.println(line); } } } } catch(IOException e){System.out.println("SERVER SIDE: Unable send/receive data");} try { serverInput.close(); serverOutput.close(); clientSocket.close(); serverSocket.close(); } catch(IOException e){System.out.println(e);} } } </code></pre> <p>Here is the client</p> <pre><code>import java.io.*; import java.net.*; public class TCPClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("localhost", 2012); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host"); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O"); System.exit(1); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); if(userInput.equals("exit")) break; } out.close(); in.close(); stdIn.close(); echoSocket.close(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload