I wonder how to change my program so that several clients can connect.
The server is to take the numbers from the clients and calculate the average and then return the value.
Is it enough to make a list to write down the numbers and then calculate the mean or is there any other way to solve this problem?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
private final static String HOST = "localhost";
private final static int PORT = 2300;
private final static Scanner SCANNER = new Scanner(System.in);
private static Socket socket;
private static PrintWriter out;
private static BufferedReader in;
private boolean isRunning;
public Client() {
isRunning = true;
}
public void makeRequests() {
while (isRunning) {
try {
socket = new Socket(HOST, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Input number: ");
int requestedNumber = SCANNER.nextInt();
out.println(requestedNumber);
String response = in.readLine();
System.out.println("Response: " + response);
if (response.equals("The number is correct!")) {
System.out.println("Closing the client.");
System.exit(1);
}
} catch (UnknownHostException e) {
System.out.println("Could not find host.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not get a response.");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Client client = new Client();
client.makeRequests();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server extends Thread {
private String serverName;
private ServerSocket ss;
private BufferedReader in;
private PrintWriter out;
private int randomNumber;
private volatile boolean isRunning;
public Server(String serverName, ServerSocket ss) {
this.serverName = serverName;
this.ss = ss;
System.out.println("Server started: " + serverName + "listening at port: " + ss.getLocalPort());
isRunning = true;
randomNumber = generateRandomNumber(10);
start(); // Uruchomienie wÄ…tku
}
public int generateRandomNumber(int range) {
return new Random().nextInt(range);
}
public void run() {
while (isRunning) {
try {
Socket connection = ss.accept();
System.out.println("Connection established on server: " + serverName);
serviceRequests(connection);
} catch (IOException e) {
System.out.println("Connection closed.");
e.printStackTrace();
}
}
try {
ss.close();
System.out.println("Connection closed.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void serviceRequests(Socket connection) throws IOException {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
out = new PrintWriter(connection.getOutputStream(), true);
try {
int requestNumber = Integer.parseInt(in.readLine());
if (requestNumber > this.randomNumber) {
System.out.println("The client guessed: " + requestNumber + ". Too high");
makeResponse("too high.");
} else if (requestNumber < this.randomNumber) {
System.out.println("The client guessed: " + requestNumber + ". Too low.");
makeResponse("too low.");
} else {
System.out.println("The client guessed: " + requestNumber);
System.out.println("CONGRATULATIONS, CORRECT!");
makeResponse("correct!");
ss.close();
}
} catch (NumberFormatException e) {
System.out.println("Could not parse request to integer.");
}
}
private void makeResponse(String message) throws IOException {
out.println("The number is " + message);
}
public static void main(String[] args) {
try {
InetSocketAddress isa = new InetSocketAddress("localhost", 2300);
ServerSocket ss = new ServerSocket();
ss.bind(isa);
new Server("test", ss);
} catch (IOException e) {
System.out.println("Could not create server socket.");
e.printStackTrace();
}
}
}
Related
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){}
}
}
I have made a chat server using socket that can handle multiple clients and can reply to individual clients..the client can chat only with the server..But as the number client increases, the server has to click send button as same as the client's number.....i.e; one click to reply when there is only one client connected...click twice when there is two clients and so on..... how can i solve it???
The server is like:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.swing.SwingUtilities;
public class NewClass1{
private static ServerSocket serverSocket = null;
static Socket clientSocket = null;
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
private static LinkedHashMap<String, clientThread> hm = new LinkedHashMap<String, clientThread>();
public static HashMap<String, clientThread> getinfo(){
return hm;
}
public static void main(String args[]) {
int portNumber = 22222;
if (args.length < 1) {
System.out.println("Usage: java MultiThreadChatServerSync <portNumber>\n"
+ "Now using port number=" + portNumber);
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
System.out.println("hiiiiiiiiiii");
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class clientThread extends Thread {
static String clientName = null;
private BufferedReader br=null;
private DataInputStream is = null;
private PrintStream os = null;
private static Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
private static HashMap<String, clientThread> hm = new HashMap<>();
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
this.hm=NewClass1.getinfo();
}
public void run() {
final int maxClientsCount = this.maxClientsCount;
final clientThread[] threads = this.threads;
try {
br= new BufferedReader(new InputStreamReader(System.in));
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.flush();
String name;
while (true) {
os.println("Enter your name.");
name = is.readLine().trim();
if (name.indexOf('#') == -1) {
break;
} else {
os.println("The name should not contain '#' character.");
}
}
System.out.println("\n"+name+" has joined");
os.println("Welcome " + name
+ " to our chat room.\nTo leave enter /quit in a new line.");
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] == this) {
clientName = "#"+name;
hm.put(clientName, this);
break;
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** A new user " + clientName
+ " entered the chat room !!! ***");
}
}
}
new Thread(new New()).start();
while(true){
String line=br.readLine();
if (line.startsWith("#")) {
String[] words = line.split("\\s", 2);
if (words.length > 1 && words[1] != null) {
words[1] = words[1].trim();
if (!words[1].isEmpty()) {
for(Map.Entry<String,clientThread> e:hm.entrySet()){
if(words[0].equals(e.getKey())){
clientThread get=e.getValue();
get.os.println("Server:\t" + words[1]);
os.flush();
System.out.println("\nServer to "+e.getKey()+":\t"+words[1]);
break;
}
else{
continue;
}
}
}}}
else { System.out.println("Please type #recipent's name.");
}}
} catch (IOException e) {
}
}
}
class New extends Thread{
public void run(){
DataInputStream is = null;
try {
is = new DataInputStream(NewClass1.clientSocket.getInputStream());
String lin=null;
while((lin=is.readLine())!=null)
{
//lin=is.readLine();
System.out.println(clientThread.clientName+": "+lin);
}
} catch (IOException ex) {
Logger.getLogger(New.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
is.close();
} catch (IOException ex) {
Logger.getLogger(New.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
The client is like:
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class NewClass implements Runnable {
// The client socket
private static Socket clientSocket = null;
// The output stream
private static PrintStream os = null;
// The input stream
private static DataInputStream is = null;
private static BufferedReader inputLine = null;
private static boolean closed = false;
public static void main(String[] args) {
// The default port.
int portNumber = 22222;
// The default host.
String host = "localhost";
if (args.length < 2) {
System.out
.println("Usage: java MultiThreadChatClient <host> <portNumber>\n"
+ "Now using host=" + host + ", portNumber=" + portNumber);
} else {
host = args[0];
portNumber = Integer.valueOf(args[1]).intValue();
}
/*
* Open a socket on a given host and port. Open input and output streams.
*/
try {
clientSocket = new Socket(host, portNumber);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host "
+ host);
}
/*
* If everything has been initialized then we want to write some data to the
* socket we have opened a connection to on the port portNumber.
*/
if (clientSocket != null && os != null && is != null) {
try {
/* Create a thread to read from the server. */
new Thread(new NewClass()).start();
while (!closed) {
String msg=inputLine.readLine();
os.println(msg.trim());
os.flush();
System.out.println("\nClient: \t"+msg);
}
/*
* Close the output stream, close the input stream, close the socket.
*/
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
/*
* Create a thread to read from the server. (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run() {
/*
* Keep on reading from the socket till we receive "Bye" from the
* server. Once we received that then we want to break.
*/
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println("\n"+responseLine);
if (responseLine.indexOf("*** Bye") != -1)
break;
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
I'm creating an "echo" server that upon receiving a message simply sends it back. I have managed to get multi-client working, but I want to make some kind of disconnect detection. I tried to get it working through sending a single character from the server, then replying with another character from the client. I couldn't get this to work, though.
How would you suggest I go about disconnect detection?
MessageServer.java
import java.net.*;
import java.io.*;
public class MessageServer {
static int clientCount = 0;
public static void main(String[] args) throws IOException {
try(ServerSocket servSocket = new ServerSocket(16384)){
while(true){
Socket socket = servSocket.accept();
addClient();
new ServerThread(socket, clientCount).start();
}
} catch(IOException e) {
System.out.println("Exception caught when trying to listen on port 16384 or listening for a connection");
System.out.println(e.getMessage());
}
}
public static void addClient(){
clientCount++;
}
}
ServerThread.java
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
private Socket cltSocket;
private BufferedReader in;
private PrintWriter out;
private int num;
public ServerThread(Socket clientSocket, int count) {
cltSocket = clientSocket;
num = count;
}
public void run() {
String input;
try {
out = new PrintWriter(cltSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cltSocket.getInputStream()));
System.out.println("Client " + num + " connected!");
while(cltSocket.isConnected() && !cltSocket.isClosed()){
if(in.ready()){
input = in.readLine();
if(input != null && !(input.equalsIgnoreCase("exit"))){
System.out.print("New input: ");
System.out.println(input);
out.println(input);
out.flush();
} else if(input.equalsIgnoreCase("exit")){
disconnect();
}
}
}
} catch(SocketException e) {
disconnect();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void disconnect(){
System.out.println("Client " + num + " disconnected!");
out.close();
try {
in.close();
cltSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MessageClient.java
import java.net.*;
import java.io.*;
public class MessageClient {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Invalid parameters! Format as: (hostname) (port)");
System.exit(1);
}
String hostname = args[0];
int port = Integer.parseInt(args[1]);
try {
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connected!");
while(socket.isConnected() && !socket.isClosed()){
String output;
if(con.ready()) {
output = con.readLine();
out.println(output);
if(output.equalsIgnoreCase("exit")) {
socket.close();
}
}
if(in.ready()){
String li = in.readLine();
if(li != null) {
System.out.println(li);
}
}
}
System.out.println("Disconnected!");
con.close();
out.close();
in.close();
System.exit(0);
} catch(SocketException e) {
System.err.println("Socket error:" + e);
} catch(UnknownHostException e) {
System.err.println("Invalid host");
} catch(IOException e) {
System.err.println("IO Error: " + e);
}
}
}
There is a way to do that:
if you read the BufferedReader by calling BufferedReader.getLine() and the other side socket is gone, then you get an SocketException... that is a way to check a lost connection
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();
}
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.