polling a database in a web server using a java application - java

i am trying to poll a database in a server and check if any new records are added, and if any i'm going to send a http request to the java application with the new record.
This is the GET request:
public class PHPDataChecker implements Runnable {
public static String output;
public void run(){
try {
URL url = new URL("http://taxi.net/login.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm using a scheduler and here is that code:
public class Main {
private static boolean canStop=false;
public static void stopPHPDataChecker() {
canStop=true;
}
public static void runnner() {
// Setup a task for checking data and then schedule it
PHPDataChecker pdc = new PHPDataChecker();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(pdc, 0L, 10L, TimeUnit.MILLISECONDS);// Start schedule
scheduler.schedule(new Runnable() {
public void run() {
System.out.println(">> TRY TO STOP!!!");
pdcHandle.cancel(true);
Main.stopPHPDataChecker();
System.out.println("DONE");
}
}, 10L, TimeUnit.MILLISECONDS);
do {
if (canStop) {
scheduler.shutdown();
}
} while (!canStop);
System.out.println("END");
}
another two programs to periodically poll it
RunMain.java:
public class RunMain implements Runnable {
public void run(){
Main m=new Main();
m.runnner();
}}
checkSchedule.java:
public class checkSchedule {
public static void main(String[] args) {
RunMain m = new RunMain();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> pdcHandle = scheduler.scheduleAtFixedRate(m, 0L, 10L, TimeUnit.SECONDS);
}
}
This doensn't poll the database correctly is there anything wrong with the codings ?
this is the output i see in the nebeans IDE
Output from Server ....
{"return":"0"}
Output from Server ....
{"return":"0"}
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END
TRY TO STOP!!!
DONE
END

Related

MulServer - Client communication: After a shutdown, connected clients can still interact[WHY?]

UPDATE: Thank you very Antoniossss and Peter Lawrey!
I created a Multi-Threaded Server - Client Communication.
I have 3 Classes: Server, Client, RequestHandler.
The server opens a ServerSocket and then starts to listen for clients via accept() and if a client connects, he refers the client's task(some String) to the RequestHandler.
The command important to me is "SHUTDOWN".
If the RequestHandler finds this command, he calls a method within the Server to shutdown.
This method is based on the usage Example of the Executor Service:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html (if you do not want to click on the link, see the FAT text for the method)
You do not have to read the code provided below, but in case someone is interested in it I am providing it
The method of the usage Example:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
public class MulServer_v1 {
protected static int portNumber = 8540;
protected static int max_Clients = 3;
protected static boolean shutdownFlag = false;
private static ServerSocket serverSocket;
protected ExecutorService executor;
protected static ArrayList<Socket> socketList = new ArrayList<>();
public MulServer_v1(int portNumber, int poolSize) {
}
public void runServer() {
try {
serverSocket = new ServerSocket(portNumber);
executor = Executors.newFixedThreadPool(max_Clients);
} catch (IOException e) {
System.out.println("Could not create server on specific port");
e.printStackTrace();
}
while (!shutdownFlag) {
try {
Socket clientSocket = serverSocket.accept();
socketList.add(clientSocket);
executor.submit(new RequestHandler_v1(clientSocket));
} catch (IOException e) {
System.out.println("Couldn't accept on the Socket");
executor.shutdown();
e.printStackTrace();
}
}
shutdownAndAwaitTermination();
}
public void shutdownAndAwaitTermination() {
System.out.println("Shutting down..");
executor.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
executor.shutdownNow();
// Cancel currently executing tasks
System.out.println("komme ich hierhin?");
// Wait a while for tasks to respond to being cancelled
if (!executor.awaitTermination(10, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
try {
serverSocket.close();
} catch (IOException e) {
System.out.println("Serversocket konnte nicht geschlossen werden");
e.printStackTrace();
}
System.out.println("I got here!");
for (Socket s : socketList) {
if (s != null) {
try {
s.close();
} catch (IOException e) {
System.out.println("Couldn't close the socket");
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MulServer_v1 server = new MulServer_v1(portNumber, max_Clients);
server.runServer();
}
}
public class Client_v1 {
public static final String HOSTNAME = "localhost";
public static final int PORTNUMBER = 8540;
private static boolean clientClose = false;
public static void main(String[] args) throws IOException {
System.out.println("Client started");
try (Socket socket = new Socket(HOSTNAME, PORTNUMBER);
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true);
// InputStream test = echoSocket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in))) {
String userInput;
while ((userInput = stdIn.readLine()) != null && !clientClose) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
// if (userInput.equals("BYE")) {
// break;
// }
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + HOSTNAME);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to "
+ HOSTNAME);
System.exit(1);
}
}
protected static void closeClient() {
clientClose = true;
}
}
public class RequestHandler_v1 implements Runnable {
// private final String password = "passwort";
private final Socket client;
private boolean closeFlag = false;
public RequestHandler_v1(Socket client) {
this.client = client;
}
#Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));) {
System.out.println("Thread started with name:"
+ Thread.currentThread().getName());
String userInput;
String serverResponse;
while ((userInput = in.readLine()) != null) {
serverResponse = processInput(userInput);
System.out.println("Received message from "
+ Thread.currentThread().getName() + " : " + userInput);
writer.write("Sever Response : " + serverResponse);
writer.newLine();
writer.flush();
if (closeFlag) {
Client_v1.closeClient();
MulServer_v1.socketList.remove(client);
client.close();
}
}
} catch (IOException e) {
System.out.println("I/O exception: " + e);
} catch (Exception ex) {
System.out.println("Exception in Thread Run. Exception : " + ex);
}
}
public String processInput(String input) {
boolean commandFound = false;
String output = "";
try {
if (input.getBytes("UTF-8").length > 255)
output = "Max string length exceeded";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Pattern allPattern = Pattern
.compile("(?<lower>^LOWERCASE\\s.+)|(?<upper>^UPPERCASE\\s.+)|(?<reverse>^REVERSE\\s.+)|(?<bye>^BYE)|(?<shutdown>^SHUTDOWN passwort)");
Matcher allMatcher = allPattern.matcher(input);
if (allMatcher.find()) {
String lower = allMatcher.group("lower");
String upper = allMatcher.group("upper");
String reverse = allMatcher.group("reverse");
String bye = allMatcher.group("bye");
String shutdown = allMatcher.group("shutdown");
commandFound = true;
if (lower != null) {
output = lower.substring(10).toLowerCase();
}
if (upper != null) {
output = upper.substring(10).toUpperCase();
}
if (reverse != null) {
output = new StringBuilder(reverse.substring(8)).reverse()
.toString();
}
if (bye != null) {
output = "BYE";
closeFlag = true;
}
if (shutdown != null) {
output = "SHUTDOWN";
MulServer_v1.shutdownFlag = true;
closeFlag = true;
}
} else {
commandFound = false;
output = "UNKNOWN COMMAND";
}
if (commandFound) {
output = "OK ".concat(output);
} else {
output = "ERROR ".concat(output);
}
return output;
}
}
Now the shutting down works, but new clients can connect after the shutdown. How is that possible?
This is Sysout I used to check:
Shutting down..
Thread started with name:pool-1-thread-3
Received message from pool-1-thread-3 : . //<--This (Sending a message) should //NOT be able to happen, since executor.shutdown(); has already been called.
The thing is that your signaling is broken:
while (!shutdownFlag) {
try {
Socket clientSocket = serverSocket.accept();
executor.execute(new RequestHandler_v1(clientSocket));
} catch (IOException e) {
accept() is blocking operation - it blocks until new connection comes right? And here is the culrpit. After you send your "shutdown" command, current thread will unblock, submit the tast, pass the while condition and block again on accept(). After this, proper executor will set the flag to false, but server is still accepting so pool is never shut down.
Another attempt to connect should wake the server and honor shutdownFlag breaking out of the loop and causing all handlers to die after 10 seconds.
Also:
while ((userInput = in.readLine()) != null) {
is a blocking operation - it block your tasks from finishing thus pool will newer shut down. null will be returned if stream will end - either naturally or by an exception. You are not ending the stream on neither of sides. So it will block.
ExecutorsService#shutdownNow() does not mean that threads from pool will be killed - they are signalled to terminate, and threads are to gracefully terminate just like #PeterLawrey mentioned, using Thread.isTerminated() flag.
Proof of concept that closing the socket will break from blocked IO operation:
public class Buffers {
private static Socket client;
static class ServerThread extends Thread {
#Override
public void run() {
try {
ServerSocket serverS = new ServerSocket(1099);
client = serverS.accept();
client.getOutputStream().write('a');
client.getOutputStream().flush();
Thread.sleep(2000);
client.close();
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class ClientThread extends Thread {
#Override
public void run() {
try {
Thread.sleep(500);
Socket socket = new Socket("127.0.0.1", 1099);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Will try to read");
String line=null;
while ((line = input.readLine()) != null) { // block here
System.out.println("Read " + line); // will never come here
}
} catch (Exception e) {
System.out.println("Server closed the connection!");
}
super.run();
}
}
public static void main(String[] args) throws InterruptedException {
new ServerThread().start();
ClientThread t = new ClientThread();
t.start();
t.join();
}
If you comment client.close(); app will never end just like in your case.

how to solve the bug in picture download thread?

In my code,first I access an address and I got the text file. In that, there are many picture links, such as http://dnight-math.stor.sinaapp.com/%E5%9C%B0%E7%90%861_img004.jpg. I use regular expression to find all the links to make a arraylist. Then I use downloadService to download all the pictures. When I first press a button to download ,it can run successfully. But it doesn't work if the button is pressed again and throws error. I think this bug is about thread but I don't know how to solve it.
HttpUtil.sendHttpRequest(address,
new HttpCallbackListener() {
#Override
public void onFinish(String response) {
try {
ArrayList<String> urlList = new ArrayList<>();
Pattern p = Pattern.compile("http:.*?.com/(.*?.(jpg|png))");
Matcher m = p.matcher(response);
StringBuffer buffer = new StringBuffer();
while (m.find()) {
m.appendReplacement(buffer, "<T>" + + m.group(1) + "</T>");
urlList.add(m.group());
}
m.appendTail(buffer);
response = buffer.toString();
Message m2 = Message.obtain();
m2.obj = response;
m2.what = 1;
mHandler.sendMessage(m2);
new DownloadService("/data/data/com.baodian/files",
urlList,
new DownloadStateListener() {
#Override
public void onFinish() {
}
#Override
public void onFailed() {
}
}, context).startDownload();
;
// JSONObject singleChoice=all.getjson
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onError(Exception e) {
}
});
public class HttpUtil {
public static void sendHttpRequest(final String address,
final HttpCallbackListener listener) {
new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection connection=null;
try {
URL url=new URL(address);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"gbk"));
StringBuilder response=new StringBuilder();
String line=null;
while ((line=reader.readLine())!=null) {
response.append(line);
}
if (listener!=null) {
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
}
}
}).start();
}
}
If you look at SimY4's answer here,
he says that the error you're getting "means the thread pool is busy and queue is full as well".
What you currently do is call onFailed when you encounter the error. What you can do is implement
a supplementary enqueing scheme. You can cache the newer urls until the thread queue has space, create and enqueue
the new threads at that point.
The following thread might prove useful : Java executors: how to be notified, without blocking, when a task completes?

Java Gui Thread Coding?

I got problem when my server connected to the client this exception is occur then my program not respond after connected. I use netbeans gui designer to generated code for gui class. I also comment the line number which show in exception below in my code for you guys considering. Everything work find before socket accept. Please help!
Exception in thread "Thread-0" java.lang.NullPointerException at
serverui.ServerUi.StartServer(ServerUi.java:62) at
serverui.ServerThread.run(ServerUi.java:19) at
java.lang.Thread.run(Thread.java:745)
class ServerThread implements Runnable{
public void run(){
try {
ServerUi t = new ServerUi();
t.StartServer(); //Line 19
} catch (IOException ex) {
//Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
//Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class ServerUi {
byte s = 0;
static ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
BufferedReader in = null;
public static boolean checklisten = false;
static gui winframe = null;
public static void main(String[] args)throws IOException {
winframe = new gui();
serverSocket = new ServerSocket(10007);
Thread tserver = new Thread(new ServerThread());
tserver.start();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
winframe.setVisible(true);
}
});
}
public void StartServer()throws IOException, InterruptedException
{
winframe.displayMessage("Listening for Connection");
clientSocket = serverSocket.accept();
winframe.displayMessage("Connected");
String inputLine;
while(true){
while((inputLine=in.readLine()) != null) // Line 62
{
winframe.displayMessage("Server: "+ inputLine);
out.println(inputLine);
if(inputLine.equals("Bye."))
{
this.Closeconnection();
break;
}
if(winframe.checkdisconnectbtn == true)
{
this.Closeconnection();
break;
}
}
}
}
You never initialize your BufferedReader.
BufferedReader in = null;
... therefore this line fails with a NullPointerException:
while((inputLine=in.readLine()) != null) // Line 62
In general, whenever you see a NullPointerException, all you have to do is look at the line and check all the objects which are invoking methods for null.
You didn't initialize in.
in = new BufferedReader(arguments);

Java threads not starting / working as expected

I am implementing a simple client-server architecture where multiple clients should be able to connect to the server and strings could be exchanged between the server and client.
My idea is that I'll have two threads on each side: a listener, constantly checking if there is anything new in the inputstream, and a writer thread, that writes into the socket if there is something to write.
However, the second thread doesn't even start... Only the first sysout is displayed.
//start new thread to handle client input
new Thread(
new ServerWorker(clientSocket, this, this.getIdCounter())).start();
System.out.println("server side listener started");
//start new thread to handle client output
new Thread(new ServerWorkerListener(clientSocket)).start();
System.out.println("server side writer started");
Here is some code from the ServerWorker:
public void run() {
try {
OutputStream output = clientSocket.getOutputStream();
while (true) {
// output.write(("Pling!\n\n").getBytes());
for (Client tempClient : server.getClientList()) {
if ((tempClient.getId() == this.id)
&& tempClient.isShouldSend()) {
output.write((tempClient.getOutputStream() + "\n\n")
.getBytes());
tempClient.setInputStream("");
tempClient.setShouldSend(false);
}
}
}
} catch (IOException e) {
System.out.println("Error in serverWorker");
e.printStackTrace();
}
}
I really don't know what I'm missing...
Whole of ServerWorker:
public class ServerWorker implements Runnable {
protected Socket clientSocket = null;
protected String serverText = null;
protected int id;
protected Server server;
public ServerWorker(Socket clientSocket, Server server,
int id) {
this.clientSocket = clientSocket;
this.serverText = serverText;
this.id = id;
this.server = server;
}
public void run() {
try {
OutputStream output = clientSocket.getOutputStream();
while (true) {
// output.write(("Pling!\n\n").getBytes());
for (Client tempClient : server.getClientList()) {
if ((tempClient.getId() == this.id)
&& tempClient.isShouldSend()) {
output.write((tempClient.getOutputStream() + "\n\n")
.getBytes());
tempClient.setInputStream("");
tempClient.setShouldSend(false);
}
}
}
} catch (IOException e) {
System.out.println("Error in serverWorker");
e.printStackTrace();
}
}
}
Whole of ServerWorkerListener:
public class ServerWorkerListener implements Runnable {
private BufferedReader input;
private Socket clientSocket;
public ServerWorkerListener(Socket clientSocket) {
this.clientSocket = clientSocket;
run();
}
#Override
public void run() {
System.out.println("its running");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
System.out.println("it's looping");
String inputLine = null;
if ((inputLine = in.readLine()) != null) {
JOptionPane.showMessageDialog(null, inputLine, "InfoBox: "
+ "Message from client",
JOptionPane.INFORMATION_MESSAGE);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about client");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to client");
System.exit(1);
}
}
}
You are invoking run() inside the constructor of ServerWorkerListener, which you must not do. The new thread ought to invoke run(), otherwise, since it contains an infinite loop, it will never return from the constructor and hence never invoke the Thread’s constructor, not to speak of its start method. So removing run() the invocation from the constructor should solve the problem.

Why is it my code cannot run many clients in java multithreading?

Why is this code nott accumulating many clients?
I'm new to java.
It only runs for only 1 client.
Can anyone explain why it doesn't support multiple clients for socket programming?
import java.net.*;
import java.io.*;
/**
* Demo Server: Contains a multi-threaded socket server sample code.
*/
public class ServerDemo extends Thread
{
final static int _portNumber = 5559; //Arbitrary port number
public static void main(String[] args)
{
try {
new ServerDemo().startServer();
} catch (Exception e) {
System.out.println("I/O failure: " + e.getMessage());
e.printStackTrace();
}
}
public void startServer() throws Exception {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(_portNumber);
} catch (IOException e) {
System.err.println("Could not listen on port: " + _portNumber);
System.exit(-1);
}
while (listening) {
handleClientRequest(serverSocket);
}
serverSocket.close();
}
private void handleClientRequest(ServerSocket serverSocket) {
try {
new ConnectionRequestHandler(serverSocket.accept()).run();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Handles client connection requests.
*/
public class ConnectionRequestHandler implements Runnable{
private Socket _socket = null;
private PrintWriter _out = null;
private BufferedReader _in = null;
public ConnectionRequestHandler(Socket socket) {
_socket = socket;
}
public void run() {
System.out.println("Client connected to socket: " + _socket.toString());
try {
_out = new PrintWriter(_socket.getOutputStream(), true);
_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
String inputLine, outputLine;
BusinessLogic businessLogic = new BusinessLogic();
outputLine = businessLogic.processInput(null);
_out.println(outputLine);
//Read from socket and write back the response to client.
while ((inputLine = _in.readLine()) != null) {
outputLine = businessLogic.processInput(inputLine);
if(outputLine != null) {
_out.println(outputLine);
if (outputLine.equals("exit")) {
System.out.println("Server is closing socket for client:" + _socket.getLocalSocketAddress());
break;
}
} else {
System.out.println("OutputLine is null!!!");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally { //In case anything goes wrong we need to close our I/O streams and sockets.
try {
_out.close();
_in.close();
_socket.close();
} catch(Exception e) {
System.out.println("Couldn't close I/O streams");
}
}
}
}
/**
* Handles business logic of application.
*/
public static class BusinessLogic {
private static final int LoginUserName = 0;
private static final int LoginPassword = 1;
private static final int AuthenticateUser = 2;
private static final int AuthSuccess = 3;
private int state = LoginUserName;
private String userName = null;
private String userPassword = null;
public String processInput(String clientRequest) {
String reply = null;
try {
if(clientRequest != null && clientRequest.equalsIgnoreCase("login")) {
state = LoginPassword;
}if(clientRequest != null && clientRequest.equalsIgnoreCase("exit")) {
return "exit";
}
if(state == LoginUserName) {
reply = "Please Enter your user name: ";
state = LoginPassword;
} else if(state == LoginPassword) {
userName = clientRequest;
reply = "Please Enter your password: ";
state = AuthenticateUser;
} else if(state == AuthenticateUser) {
userPassword = clientRequest;
if(userName.equalsIgnoreCase("John") && userPassword.equals("doe")) {
reply = "Login Successful...";
state = AuthSuccess;
} else {
reply = "Invalid Credentials!!! Please try again. Enter you user name: ";
state = LoginPassword;
}
} else {
reply = "Invalid Request!!!";
}
} catch(Exception e) {
System.out.println("input process falied: " + e.getMessage());
return "exit";
}
return reply;
}
}
}
You are not starting the thread in your code.
instead of
new ConnectionRequestHandler(serverSocket.accept()).run();
call
new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();
method run() of your Runnable class will be invoked when you start your thread, you should not call this run() method directly.
Instead of that you should make a thread instance via
Thread myThread = new Thread(aRunnableInstance);
and start it:
myThread.start();
You're not starting a new thread, but simply running the RequestHandler code in the main thread.
Look up the difference between Thread.start() and Runnable.run(). This question might help.
Edit:
You're just missing the part where you would tell the JVM to create a new Thread to execute your Runnable code. Without a call to Thread.start() your current (and only) thread would be busy handling one request at a time. You want one Thread per request, basically. There are more advanced ways of doing this (thread pools and whatnot), but this should get you started.
private void handleClientRequest(ServerSocket serverSocket) {
try {
new Thread(ConnectionRequestHandler(serverSocket.accept())).start();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories