thread sleep makes main server to sleep - java

I want to write a java multithreaded server. I used this code:
MultiThreadedServer.java :
package servers;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class MultiThreadedServer implements Runnable{
protected int serverPort = 8080;
protected ServerSocket serverSocket = null;
protected boolean isStopped = false;
protected Thread runningThread= null;
public MultiThreadedServer(int port){
this.serverPort = port;
}
public void run(){
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection", e);
}
System.out.println("Request Entered: " + System.currentTimeMillis());
new Thread(
new WorkerRunnable(
clientSocket, "Multithreaded Server")
).start();
}
System.out.println("Server Stopped.") ;
}
private synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop(){
this.isStopped = true;
try {
this.serverSocket.close();
} catch (IOException e) {
throw new RuntimeException("Error closing server", e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 8080", e);
}
}
}
WorkerRunnable.java:
package servers;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.net.Socket;
public class WorkerRunnable implements Runnable{
protected Socket clientSocket = null;
protected String serverText = null;
public WorkerRunnable(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " + this.serverText + " - " +time +"").getBytes());
Thread.sleep(2000);
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException | InterruptedException e) {
//report exception somewhere.
e.printStackTrace();
}
}
}
I used this code to run main server:
MultiThreadedServer server = new MultiThreadedServer(9000);
new Thread(server).start();
then I opened 3 tabs in the web browser and entered http://localhost:9000/ in all of them.
but tabs doesn't run concurrently and responses are received after 2 sec of each other.
I found out that when I run "Thread.sleep" in each WorkerRunnable thread, MultiThreadedServer doesn't accept any request anymore.
Any solution to run all threads concurrently?

Related

Java: Socket Closed Error while using thread

I am building a multithread chat server.
The multi-threaded server (Manager Class) could serve many clients. It receives a message from a client, and broadcast to all clients.
The client (Peer Class) have two threads - SendThread for sending a message to the server. ReceiveThread to listen to the server broadcast.
However, while running the client program, it catches the exception and says that socket closed.
My code for the server class is below:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Manager {
public int port;
public ArrayList<Socket> clients;
public Manager(int port) throws IOException {
this.port = port;
this.clients = new ArrayList<>();
try (ServerSocket server = new ServerSocket(port)){
System.out.println("Waiting for client connection-");
while (true){
Socket client = server.accept();
clients.add(client);
System.out.println("Client applies for connection");
Thread t = new Thread(new serverClientThread(client));
t.start();
}
}
}
public class serverClientThread implements Runnable {
private Socket client;
public serverClientThread(Socket client){
this.client = client;
}
#Override
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
while (true){
// read
String line = reader.readLine();
if (line != null){
System.out.println("I received "+line);
// write
// broadcast
broadcast("I received " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// broadcast the message to all clients
public synchronized void broadcast(String message) throws IOException {
for (Socket client:this.clients){
if (client.isClosed()){
continue;
}
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()))){
writer.write("I received " + message);
writer.newLine();
writer.flush();
}
}
}
}
The code of the client class is below:
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Peer {
public String hostname;
public int port;
public Peer(String hostname, int port){
this.hostname = hostname;
this.port = port;
try (Socket socket = new Socket(hostname, port)){
// create writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread t1 = new Thread(new SendThread(writer));
Thread t2 = new Thread(new ReceiveThread(reader));
t1.start();
t2.start();
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public class SendThread implements Runnable{
private BufferedWriter writer;
public SendThread(BufferedWriter writer){
this.writer = writer;
}
#Override
public void run() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a String: ");
String str = sc.nextLine();
// send to server
if (str != null){
try {
this.writer.write(str);
this.writer.newLine();
this.writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class ReceiveThread implements Runnable{
private BufferedReader reader;
public ReceiveThread(BufferedReader reader){
this.reader = reader;
}
#Override
public void run() {
while (true){
String res = null;
try {
res = this.reader.readLine();
if (res != null){
System.out.println("Server response: "+ res);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
}
}
The error message is:
java.net.SocketException: Socket closed
at java.base/java.net.SocketInputStream.socketRead0(Native Method)
at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:115)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
at Peer$ReceiveThread.run(Peer.java:86)
at java.base/java.lang.Thread.run(Thread.java:834)
It occurs in ReceiveThread in the Peer class.
Any bits of help is appreciated. Thank you!
Yige
Since you are using a try-with-resources, the socket is automatically closed immediately after you start t1 and t2.
You can think of
try (Socket socket = new Socket(hostname, port)){
// [...]
t1.start();
t2.start();
}
//
like this:
Socket socket;
try {
socket = new Socket(hostname, port)
// [...]
t1.start();
t2.start();
} catch (/* [...] */) {
} finally {
if (socket != null) {
socket.close(); // <- here the socket is closed
}
}
And since the thread is running in the background, t1.start() does not wait until thread-1 has finished -> the socket is closed.
Without try-with-resources:
public class Peer {
private Socket socket;
// [...]
public Peer(String hostname, int port) {
// [...]
try {
this.socket = new Socket(hostname, port);
// [...]
} catch (UnknownHostException | IOException ex) {
ex.printStackTrace();
System.exit(-1);
}
}
// Call this method when your program exits
public void close() {
if (this.socket != null) {
this.socket.close();
}
}
}

Java Concurrent Socket Programming

Below is my code for a simple Concurrent Server. Whenever I run multiple clients, the server only prints out the input of the first client. I'm not sure what I've done wrong. Any help would be appreciated.
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
inputStream = new BufferedReader(new InputStreamReader(concurrentSocket.getInputStream()));
outputStream = new PrintWriter(new OutputStreamWriter(concurrentSocket.getOutputStream()));
String testString = inputStream.readLine();
System.out.println(testString);
} catch (IOException i){}
}
This code might help you to understand how to run multiple clients concurrently. :)
What this code does? TCP Client sends a string to the server and TCP server sends back the string in UPPERCASE format & the server can do this concurrently with multiple connections.
I have included 3 files for the server and one more for testing the server with multiple clients(ClientTest.java)
Main.java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
new Server(3000).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;
public class Server {
private ServerSocket sSocket;
private boolean run;
private int port;
public Server(int port) throws IOException {
this.port = port;
this.sSocket = new ServerSocket(this.port);
}
public void start() {
this.run = true;
Logger.getLogger(getClass().getName()).info("Server is listening on port: " + port);
try {
while (run) {
Socket cs = sSocket.accept();
Logger.getLogger(getClass().getName())
.info("New Client Connected! " + cs.getPort());
new Thread(new Client(cs)).start(); // Put to a new thread.
}
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
public void stop() {
this.run = false;
}
}
Client.java (Client Process on server)
import java.io.*;
import java.net.Socket;
import java.util.logging.Logger;
public class Client implements Runnable {
private Socket clientSocket;
private DataOutputStream out; // write for the client
private BufferedReader in; // read from the client
public Client(Socket clientSocket) {
this.clientSocket = clientSocket;
}
#Override
public void run() {
// Do client process
outToClient(inFromClient().toUpperCase());
closeConnection();
}
private String inFromClient() {
String messageFromClient = "";
/*
* Do not use try with resources because once -
* - it exits the block it will close your client socket too.
*/
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
messageFromClient = in.readLine();
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("InFromClientErr - " + e.getMessage());
}
return messageFromClient.trim().equals("") ? "No Inputs given!" : messageFromClient;
}
private void outToClient(String message) {
try {
out = new DataOutputStream(clientSocket.getOutputStream());
out.writeBytes(message);
} catch (IOException e) {
Logger.getLogger(getClass().getName()).severe("OutToClientErr - " + e.getMessage());
}
}
private void closeConnection() {
try {
in.close();
out.close();
clientSocket.close();
} catch (NullPointerException | IOException e) {
Logger.getLogger(getClass().getName()).severe(e.getMessage());
}
}
}
ClientTest.java (For Testing clients)
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
Socket clientSocket;
try {
clientSocket = new Socket("localhost", 3000);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(new Scanner(System.in).nextLine() + '\n'); // Get user input and send.
System.out.println(inFromServer.readLine()); // Print the server response.
} catch (IOException e) {
e.printStackTrace();
}
}
}
The issue was instead with the client. Not the server. The socket was declared outside of the for loop, and therefore only one connection was being created. Like so below:
public static void main(String[] args) {
try {
socket = new Socket("127.0.0.1", 8001);
for (int i = 0; i < 5; i++){
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
The Socket should be declared inside the for loop like so:
public static void main(String[] args) {
try {
for (int i = 0; i < 5; i++){
socket = new Socket("127.0.0.1", 8001);
System.out.println("Starting client: " + i);
ConcurrentClient concurrentClient = new ConcurrentClient(socket, i);
concurrentClient.run();
}
} catch (IOException io) {
}
}
I really don't know why you need so complex structure of input and output streams. It is better to use Scanner that will wait for the new input.
Also you can use PrintWriter to output the results of your conversation.
Here is server that accepts multiple clients:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ConcurrentServer extends Thread {
private Socket concurrentSocket;
public ConcurrentServer(Socket clientSocket) {
this.concurrentSocket = clientSocket;
}
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8001);
while (true){
Socket clientSocket = serverSocket.accept();
System.out.println(clientSocket);
ConcurrentServer client = new ConcurrentServer(clientSocket);
client.start();
}
} catch (IOException i){}
}
public void run(){
try {
InputStream inputStream = concurrentSocket.getInputStream();
Scanner scanner = new Scanner(inputStream);
OutputStream outputStream = concurrentSocket.getOutputStream();
PrintWriter pw = new PrintWriter(outputStream);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
pw.println("message: " + line);
pw.flush();
}
} catch (IOException i){}
}
}

SocketException thrown when stopping my TCP Server java

Im getting this error when closing my TCP Server from my form.
java.net.SocketException: Socket closed
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:404)
at java.net.ServerSocket.implAccept(ServerSocket.java:545)
at java.net.ServerSocket.accept(ServerSocket.java:513)
at com.hightekjonathan.HomeServer.Server.Start(Server.java:36)
at com.hightekjonathan.HomeServer.Form$2.run(Form.java:81)
at java.lang.Thread.run(Thread.java:745)
Heres the Server.java:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
public class Server {
private static ServerSocket serverSocket = null;
private static Socket socket = null;
private static DataInputStream dataInputStream = null;
private static DataOutputStream dataOutputStream = null;
private static int port = 19586;
private static boolean running = false;
public void Start() {
try {
System.out.println("Starting Server...");
serverSocket = new ServerSocket(port);
System.out.println("Server Started");
System.out.println("IP Address: " + getIpAddress());
System.out.println("Listening: " + serverSocket.getLocalPort());
running = true;
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("Attempting to connect to clients...");
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("connected");
} catch (Exception e) {
e.printStackTrace();
}
}
public void Stop() {
if (running) {
if (socket != null) {
try {
socket.close();
socket = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
running = false;
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public boolean isRunning() {
return running;
}
}
Its started on a new thread from my GUI Form using this function:
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonActionPerformed(evt);
}
);
And then buttonActionPerformed() is this:
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
if (!server.isRunning()) {
Runnable r = new Runnable() {
public void run() {
server.Start();
}
};
new Thread(r).start();
button.setText("Stop Server");
serverStatus.setText("Server: Started");
} else {
server.Stop();
button.setText("Start Server");
serverStatus.setText("Server: Stopped");
}
}
The error only appears when I stop the server when no clients have connected. But when a client connects, then disconnects, I don't get that error. It properly closes it, I just want to make sure that error won't be a serious problem, or if there is an easy way of fixing it.
When you start your server, you call serverSocket.accept(). This call blocks thread until a connection is made. And by calling server.stop() you are closing this server socket in another thread. ServerSocket.close() JavaDoc says:
Any thread currently blocked in {#link #accept()} will throw a {#link SocketException}.
So thats why you are getting this exception.
I think you can just ignore this exception.
P.S.
And you should make your boolean running volatile.

"Stream closed" IOException in client-server application using java socket

my client breaks, because of "Stream closed" exception.
Server properly waits for connection, but client don't send any data because of "stream closed" Exception.
Server after waiting time echoes "Unexpected error".
Thanks for help!
My code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int PORT = 50000;
static boolean flaga = true;
private static ServerSocket serverSocket;
private static Socket clientSocket;
public static void main(String[] args) throws IOException {
serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
System.out.print("Wating for connection...");
Thread t = new Thread(new Runnable() {
public void run() {
try {
while (flaga) {
System.out.print(".");
Thread.sleep(1000);
}
} catch (InterruptedException ie) {
//
}
System.out.println("\nClient connected on port " + PORT);
}
});
t.start();
clientSocket = null;
try {
clientSocket = serverSocket.accept();
flaga = false;
} catch (IOException e) {
System.err.println("Accept failed.");
t.interrupt();
System.exit(1);
}
final PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
final BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
while (true) {
out.println("Ping");
System.out.println(System.currentTimeMillis()
+ " Ping sent");
String input = in.readLine();
if (input.equals("Pong")) {
System.out.println(System.currentTimeMillis()
+ " Pong received");
} else {
System.out.println(System.currentTimeMillis()
+ " Wrong answer");
}
Thread.sleep(5000);
}
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
}
}
});
t.start();
}
}
And Client code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
private static final int PORT = 50000;
private static final String HOST = "127.0.0.1";
public static void main(String[] args) throws IOException {
Socket socket = null;
try {
socket = new Socket(HOST, PORT);
} catch (Exception e) {
System.err.println("Could not connect to " + HOST + ":" + PORT);
System.exit(1);
}
final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
Thread t = new Thread(new Runnable() {
public void run() {
long start = System.currentTimeMillis();
try {
while (true) {
try {
String input = in.readLine();
if (input != null) {
System.out.println(System.currentTimeMillis()
+ " Server: " + input);
}
if (input.equals("Ping")) {
if (System.currentTimeMillis() - start > 30000) {
out.println("Pon g");
System.out.println(System
.currentTimeMillis()
+ " Client: Pon g");
break;
}
out.println("Pong");
System.out.println(System.currentTimeMillis()
+ " Client: Pong");
} else {
System.out.println(start);
out.println("got");
}
} catch (IOException ioe) {
System.err.println(System.currentTimeMillis() + " "
+ ioe.getMessage());
ioe.getStackTrace();
System.exit(0);
}
}
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
}
}
});
t.start();
out.close();
in.close();
socket.close();
}
}
In your client, you start the thread but directly close streams and socket:
t.start();
out.close();
in.close();
socket.close();
You can, as a test, move the stream and socket calls to the last catch block.
...
} catch (Exception e) {
System.err.println(System.currentTimeMillis()
+ " Unexpected Error");
out.close();
in.close();
socket.close();
}
}
});
t.start();
}

Java socket - simple program doesn't work

I've spent lot of time to find out where is the problem but with no success. Server is launching correctly, but when I launch Client I get "Unexpected Error" exception. I've changed ports too with no effects. What should I do to make this working?
/* Server.java */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
private static final int PORT = 50000;
static boolean flaga = true;
private static ServerSocket serverSocket;
private static Socket clientSocket;
public static void main(String[] args) throws IOException
{
serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
}
catch(IOException e)
{
System.err.println("Could not listen on port: "+PORT);
System.exit(1);
}
System.out.print("Wating for connection...");
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
while(flaga)
{
System.out.print(".");
Thread.sleep(1000);
}
}
catch(InterruptedException ie)
{
//
}
System.out.println("\nClient connected on port "+PORT);
}
});
t.start();
clientSocket = null;
try
{
clientSocket = serverSocket.accept();
flaga = false;
}
catch(IOException e)
{
System.err.println("Accept failed.");
t.interrupt();
System.exit(1);
}
final PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
final BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
t = new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(5000);
while(true)
{
out.println("Ping");
System.out.println(System.currentTimeMillis()+" Ping sent");
String input = in.readLine();
if(input.equals("Pong"))
{
System.out.println(System.currentTimeMillis()+" Pong received");
}
else
{
System.out.println(System.currentTimeMillis()+" Wrong answer");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
break;
}
Thread.sleep(5000);
}
}
catch(Exception e)
{
System.err.println(System.currentTimeMillis()+" Unexpected Error");
}
}
});
t.start();
}
}
and the Client class
/* Client.java */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client
{
private static final int PORT = 50000;
private static final String HOST = "localhost";
public static void main(String[] args) throws IOException
{
Socket socket = null;
try
{
socket = new Socket(HOST, PORT);
}
catch(Exception e)
{
System.err.println("Could not connect to "+HOST+":"+PORT);
System.exit(1);
}
final PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread t = new Thread(new Runnable()
{
public void run()
{
long start = System.currentTimeMillis();
while (true)
{
try
{
String input = in.readLine();
if (input != null)
{
System.out.println(System.currentTimeMillis() + " Server: " + input);
}
if (input.equals("Ping"))
{
if(System.currentTimeMillis()-start>30000)
{
out.println("Pon g");
System.out.println(System.currentTimeMillis() + " Client: Pon g");
break;
}
out.println("Pong");
System.out.println(System.currentTimeMillis() + " Client: Pong");
}
}
catch (IOException ioe)
{
//
}
}
}
});
t.start();
out.close();
in.close();
socket.close();
}
}
Here is the output on running
Wating for connection............
Client connected on port 50000
1368986914928 Ping sent
java.lang.NullPointerException
at Server$2.run(Server.java:84)
at java.lang.Thread.run(Thread.java:722)
You're making a big mistake with those catch blocks that are empty or print out your useless message.
You'll get more information if you print or log the stack trace. It's simply a must.
You need some intro instruction - have a look at this and see how it's different from yours.
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html
It shows your out object is null. Instead of input.equals("Pong") use input != null && input.equals("Pong") in line 84 of Server.java. I guess you would have received Pong received but in later stages when you are listening to nothing you could have got this NPE.

Categories

Resources