How do you handle multiple client to connect to one server? I have this LogServer.java
import javax.net.ssl.*;
import javax.net.*;
import java.io.*;
import java.net.*;
public class LogServer {
private static final int PORT_NUM = 5000;
public static void main(String args[]) {
ServerSocketFactory serverSocketFactory =
ServerSocketFactory.getDefault();
ServerSocket serverSocket = null;
try {
serverSocket =
serverSocketFactory.createServerSocket(PORT_NUM);
} catch (IOException ignored) {
System.err.println("Unable to create server");
System.exit(-1);
}
System.out.printf("LogServer running on port: %s%n", PORT_NUM);
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is, "US-ASCII"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException exception) {
// Just handle next request.
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignored) {
}
}
}
}
}
}
and an embedded applet with part of the code like this e.g
import java.io.*;
import java.util.logging.*;
public class LogTest
{
private static Logger logger = Logger.getAnonymousLogger();
public static void main(String argv[]) throws IOException
{
Handler handler = new SocketHandler("localhost", 5000);
logger.addHandler(handler);
logger.log(Level.SEVERE, "Hello, World");
logger.log(Level.SEVERE, "Welcome Home");
logger.log(Level.SEVERE, "Hello, World");
logger.log(Level.SEVERE, "Welcome Home");
}
}
now the question is if I run "java LogServer" on the server, it will open the application and waiting for input stream and if I open my site, it will start streaming the log. But if I open one more using other computer/network, the second site does not log the stream. seems like it's because the first one still bind to port 5000.
How do I handle this? How does socket actually work with multiple client / one server?
For every client you need to start separate thread. Example:
and
You can also go with more advanced solution, that uses NIO selectors, so you will not have to create thread for every client, but that's a bit more complicated.
See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.
Pay attention that
accept()
is not thread safe, so the call is wrapped withinsynchronized
.Here is code for Multiple Client to one Server Working Fine .. Give it a try :)
Server.java:
Client1.java:
Client2.java
This is the echo server handling multiple clients... Runs fine and good using Threads
Also here is the code for the client.. Just execute this code for as many times as you want to create multiple client..
I guess the problem is that you need to start a separate thread for each connection and call
serverSocket.accept()
in a loop to accept more than one connection.It is not a problem to have more than one connection on the same port.