Hi, I'm new to these forums. I've been trying for the past two hours to figure out why this piece of code isn't working. The client is supposed to receive a message ("two") from the server, but the client screen stays completely blank.
This is the first time I'm working with sockets, so any help on getting this thing working would be deeply appreciated. Then I can finally get to messing around with the code in order to understand how it actually works.
Client
public class SimpleClient { public static void main (String [] args) throws IOException { final int APP_PORT = 3816; Socket s = new Socket ("localhost", APP_PORT); InputStream instream = s.getInputStream (); OutputStream outstream = s.getOutputStream (); Scanner in = new Scanner (instream); PrintWriter out = new PrintWriter (outstream); out.print ("one"); String response = in.nextLine (); System.out.println (response); s.close (); } }
Server
public class SimpleServer { public static void main (String [] args) throws IOException { final int APP_PORT = 3816; ServerSocket ss = new ServerSocket (APP_PORT); System.out.println ("Waiting for clients to connect"); while (true) { Socket s = ss.accept (); System.out.println ("Client connected..."); Service service = new Service (s); Thread t = new Thread (service); t.start (); } } }
Service
public class Service implements Runnable { Socket s; Scanner in; PrintWriter out; InputStream instream; OutputStream outstream; public Service (Socket socket) {s = socket;} public void run (){ try { instream = s.getInputStream (); outstream = s.getOutputStream (); in = new Scanner (instream); out = new PrintWriter (outstream); System.out.print("Service running"); performService (); } catch (IOException ioe) { ioe.getMessage (); } } public void performService () throws IOException { while (true) { String command = in.next (); if (in.next().equalsIgnoreCase ("one")) { out.print ("server: two"); } else { out.print ("server: three"); } } } }