This is a problem I never figured out. I've asked many people, and they don't even know. Anyways, lets get to the problem. Here's what I tried to do... Create a client and a server. The client connects to the server, and sends a message to it every 3 minutes (I reduced the time for testing). There has to be two independent threads however (one for the client and server). What I found was, the client would continue to send messages, but the server would no longer listen on port 1234.
Client:
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public Client(){
startClient();
}
public void startClient(){
new Thread(new Runnable(){
@Override
public synchronized void run(){
try{
Socket sendChat = new Socket("localhost", 1234);
PrintWriter writer = new PrintWriter(sendChat.getOutputStream());
while(true){
Thread.sleep(1000); // normally 180000
writer.println("Hello Server!");
}
}catch(Exception err){
err.printStackTrace();
}
}
}).start();
}
}
Server:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public Server(){
startServer();
}
public void startServer(){
new Thread(new Runnable(){
@Override
public synchronized void run(){
try{
@SuppressWarnings("resource")
ServerSocket server = new ServerSocket(1234);
while(true){
final Socket test = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(test.getInputStream()));
while(!test.isClosed()) {
Date date = new Date();
System.out.println("Server got message from client " + date);
}
reader.close();
}
}catch(Exception err){
err.printStackTrace();
}
}
}).start();
}
}
Start:
public class Start {
public static void main(String[] args){
new Server();
new Client();
}
}
I would greatly appreciate it if someone could tell me what is wrong, because I honestly have no clue.
Write below two lines out of while
loop in Server class and it will work for you.
final Socket test = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(test.getInputStream()));
What is happening in your code : Server will wait for new client every time after completion of the while loop but there is no client which is going to connected with server at that instance. So server will wait untill a new client will come and server will accept that new client and continue its processing.