Friday, 23 August 2013

Server Socket disconnects and stops listening

Server Socket disconnects and stops listening

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.

No comments:

Post a Comment