So, I created a basic client-server program in Java. It starts as follows:
- Client connects to server
- Server asks for client name
- Customer responds with a name
- The server greets the client
- After that, the Client speaks and the Server repeats the words back
I got this to work without any problems using this tutorial . The problem occurs when I try to implement multiple clients. I thought this would work, because I use several threads, however, other clients just hang until the first client closes, and then it starts its work (the server accepts input from the second client, but does not answer everything, until until the first client completes).
Here is the code I'm using:
import java.net.*; import java.io.*; public class Server extends Thread { private ServerSocket listener; public Server(int port) throws IOException { listener = new ServerSocket(port); } public void run() { while(true) { try { Socket server = listener.accept(); DataOutputStream out = new DataOutputStream(server.getOutputStream()); out.writeUTF("What is your name?"); DataInputStream in = new DataInputStream(server.getInputStream()); String user_name = in.readUTF(); out.writeUTF("Hello "+user_name); while(true) { String client_message = in.readUTF(); out.writeUTF(client_message); } } catch(IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { int port = 6006; try { Thread t = new Server(port); t.start(); } catch(IOException e) { e.printStackTrace(); } } }
Can someone explain what I'm doing wrong?
I looked at using Runnable instead of Extends Thread, but I had even more problems, so I want to try and work with this first.
source share