Single java thread using excess system resources - java

I am trying to create a server listener. It sits back and waits for data coming from the client and performs setting actions due to the nature of the data. But right now, after receiving the first data stream, it goes into a resource hog, the memory usage shoots up and the CPU usage is maxing out a single core.
1 - How can I fix this? How can I make it listen without all the resource hog, as you can see it is a really really small program.
2 - The client itself that sends these data streams, runs once. It starts up, connects to the server, sends the data and quits. While the server is still "on", if I retry running the client again, the server doesn't receive the data.
Server Code:
package mediaserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
ServerSocket ss;
Socket s;
BufferedReader br;
public Main() throws IOException{
ss = new ServerSocket(1111);
s = ss.accept();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
new Thread(new runner()).start();
}
class runner implements Runnable{
public void run(){
while(true){
try {
String n = br.readLine();
System.out.println(n);
} catch (IOException ex) {
}
finally{
try {
s.close();
ss.close();
} catch (IOException ex) {
}
}
}
}
}
public static void main(String[] args) throws IOException {
new Main();
}
}
Client Code
package mediaserver;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class test {
public static void main(String [] args) throws UnknownHostException, IOException, InterruptedException{
Socket s = new Socket("127.0.0.1", 1111);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("");
bw.newLine();
bw.flush();
}
}

The server never gets the data on additional run because ss.accept() is only called one time. You need to wrap this in a loop:
s = ss.accept();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
new Thread(new runner()).start();

The following piece of code is an infinite loop:
while(true) {
try {
String n = br.readLine();
System.out.println(n);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
finally {
...
}
}
Once the client disconnects, the BufferedReader instance will encounter the end-of-file and readLine will return null. The loop then will continue to print null infinitely.
The fix it, check for null:
while(true) {
try {
String n = br.readLine();
if (n == null)
break;
System.out.println(n);
} catch (IOException ex) {
}
finally {
...
}
}

Related

How do I get my multithreaded server/client chat program to echo messages to all clients using sockets?

right now I have a java program that uses threads and sockets to echo text responses like a real chat window. Currently, my program works by running the server and than as many clients as I want. When a client enters a message, that message is echoed to the server and also to the client that sent the message.
My problem is that I want the message any client enters to be sent not only to the server and to themselves, but to every other client as well.
Heres how it currently works:
Server:
Received client message: test1
Client 1:
Enter message: test1
test1
Client 2:
Enter message:
Client 1 enters test1, receives test1 back and the server also receives test1. Client 2 gets nothing. My goal is to have any messages entered in the clients display on the client that sent the message as well as the other clients and server.
Working example:
Server:
Received client message: test1
Received client message: hello
Client 1:
Enter message: test1
test1
From client 2: hello
Client 2:
Enter message:
From client 1: test1
hello
The formatting doesnt have to be exactly like that, but thats the idea. My code so far is below. Ive read that I need to add my clients to a list and then loop over them and send them all the message but im not sure. Any help would be great.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Scanner;
public class EchoMultiThreadClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 4000)) {
//socket.setSoTimeout(5000);
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String echoString;
String response;
do {
System.out.println("Enter string to be echoed: ");
echoString = scanner.nextLine();
pw.println(echoString);
if(!echoString.equals("exit")) {
response = br.readLine();
System.out.println(response);
}
} while(!echoString.equals("exit"));
// }catch(SocketTimeoutException e) {
// System.out.println("The Socket has been timed out");
} catch (IOException e) {
System.out.println("Client Error: " + e.getMessage());
}
}
}
server 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;
import java.util.Vector;
public class EchoMultiThreadServer {
private static Vector<Echoer> clients = new Vector<Echoer>();
public static void main(String [] args) {
try(ServerSocket serverSocket = new ServerSocket(4000)){
while(true) {
Socket socket = serverSocket.accept();
Echoer echoer = new Echoer(socket);
echoer.start();
clients.add(echoer);
}
}catch(IOException e) {
System.out.println("Server Exception"+e.getMessage());
}
}
}
thread code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Echoer extends Thread{
private Socket socket;
public Echoer(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter wr = new PrintWriter(socket.getOutputStream(), true);
while(true) {
String echoString = in.readLine();
System.out.println("Received Client Input: " + echoString);
if(echoString.equals("exit")) {
break;
}
wr.println(echoString);
}
}catch(IOException e) {
System.out.println("Oooops " + e.getMessage());
}finally {
try {
socket.close();
}catch(IOException e) {
// later
}
}
}
}
I can see two problems with your current logic:
At the client side, you are essentially reading user input, then sending to server and getting a (single) response. So the problem here is that you only get one response, while you should take more than one for each user input line: that is the user's input plus the other users' input. Since you don't know when and how many the other users' inputs are going to be, you need to go asynchronous. I mean that you need 2 threads: one for reading user input and the other for reading server input/response (note: we are still at the client side). Since you already have one of the 2 threads, ie the one which runs the main method, then you can use it instead of creating a new one.
At the server side, your Echoer is reading user input but only sending it back to the same client. You need for example a loop to send the client's input to all other clients too.
So what would seem to me a proper logic is:
Client side:
Reading server's responses thread logic:
forever, do:
get server's message.
print server's message to user.
main method:
connect to server.
start a "Reading server's responses thread".
get user input.
while the user's input it not "exit", do:
send user's input to server.
get user input.
disconnect from server.
Server side:
Echoer thread:
forever, do:
read client's message.
for every client, do:
send the message to the client.
main method:
start server socket.
forever, do:
accept incoming connection.
start an Echoer thread for the accepted connection.
There are some missing bits though, such as how to maintain the list of all clients, but for that I can see you are already using a Vector<Echoer> clients at the server side. So just pass that Vector to every Echoer you create, so they can do the broadcasting of each incomming message. Important note here: at the server side, you have more than one threads: the main one and each Echoer, so make sure you synchronize on the Vector while you are modifying it at the main thread and also while broadcasting at the Echoers.
Notes:
I am assuming in all the above logic that there is no particular order in which the clients send their messages. For example if always client A sent first, then client B and so on, and the whole process was repeating, then you wouldn't need to go multithreading at all.
Please take your time. First implement it and then tell me if you encouter any problems.
Edit 1: full sample code.
Client code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Client {
//This is the "Reading server's responses thread" I am talking about in the answer.
private static class ReadingRunnable implements Runnable {
private final BufferedReader serverInput;
public ReadingRunnable(final InputStream is) {
serverInput = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
}
#Override
public void run() {
try {
//While the server is not disconnected, we print each line to 'System.out':
for (String line = serverInput.readLine(); line != null; line = serverInput.readLine())
System.out.println(line);
}
catch (final IOException iox) {
iox.printStackTrace(System.out);
}
finally {
System.out.println("Input from server stopped.");
}
}
}
public static void main(final String[] args) {
try {
System.out.print("Connecting... ");
try (final Socket sck = new Socket("localhost", 50505);
final OutputStream os = sck.getOutputStream();
final InputStream is = sck.getInputStream()) {
System.out.println("Connected.");
new Thread(new ReadingRunnable(is)).start();
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
final Scanner scan = new Scanner(System.in);
for (String userInput = scan.nextLine(); !"exit".equalsIgnoreCase(userInput); userInput = scan.nextLine()) {
bw.write(userInput);
bw.newLine();
bw.flush();
}
}
}
catch (final IOException iox) {
iox.printStackTrace(System.out);
}
finally {
System.out.println("Output from user stopped.");
}
}
}
Server code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Objects;
public class Server {
private static class Echoer implements Runnable {
private final ArrayList<Echoer> all;
private final BufferedWriter bw;
private final BufferedReader br;
public Echoer(final ArrayList<Echoer> all,
final InputStream is,
final OutputStream os) {
this.all = Objects.requireNonNull(all);
bw = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
}
//Instead of exposing 'bw' via a getter, I just built a helper method to send a message to the Echoer:
public void send(final String msg) throws IOException {
bw.write(msg);
bw.newLine();
bw.flush();
}
#Override
public void run() {
try {
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line); //Print the received line at the server.
synchronized (all) { //We are reading from a collection which may be modified at the same time by another (the main) Thread, so we need to synchronize.
//Broadcast the received line:
for (int i = all.size() - 1; i >= 0; --i) {
try {
all.get(i).send(line);
}
catch (final IOException iox) {
all.remove(i); //In case we cannot send to the client, disconnect him, ie remove him from the list in this simple case.
}
}
}
}
}
catch (final IOException iox) {
}
finally {
synchronized (all) {
all.remove(this); //Disconnect him, ie remove him from the list in this simple case.
}
System.out.println("Client disconnected.");
}
}
}
public static void main(final String[] args) throws IOException {
System.out.print("Starting... ");
try (final ServerSocket srv = new ServerSocket(50505)) {
final ArrayList<Echoer> all = new ArrayList<>();
System.out.println("Waiting for clients...");
while (true) {
final Socket sck = srv.accept();
try {
final OutputStream os = sck.getOutputStream();
final InputStream is = sck.getInputStream();
final Echoer e = new Echoer(all, is, os); //Pass all the Echoers at the new one.
synchronized (all) { //We will write to a collection which may be accessed at the same time by another (an Echoer) Thread, so we need to synchronize.
all.add(e); //Update list of Echoers.
}
new Thread(e).start(); //Start serving Echoer.
}
catch (final IOException iox) {
System.out.println("Failed to open streams for a client.");
}
}
}
}
}

Java socket server not responding

I am getting started with java sockets just out of inquisitiveness.
I wrote a small piece of code, a server and a client.
The server accepts a string and converts it to upper case and returns to the client.
I want the server to be able to handle multiple clients and have a persistent connection.
Here is the server code :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
private ServerSocket listener;
private ArrayList<Socket> clients;
public Server() throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(7575);
}
public Server(int port) throws IOException{
clients = new ArrayList<Socket>();
listener = new ServerSocket(port);
}
public void start() throws IOException, InterruptedException{
Thread one = new Thread(){
public void run(){
while (true){
Socket socket = null;
try {
socket = listener.accept();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (socket.isConnected()){
try {
socket.setKeepAlive(true);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clients.add(socket);
System.out.println(socket.getRemoteSocketAddress().toString());
}
}
}
};
Thread two = new Thread(){
public void run(){
try {
while (true){
work();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
one.start();
two.start();
one.join();
two.join();
stop();
}
private void stop() throws IOException{
listener.close();
}
private void work() throws IOException{
if (clients.size() == 0){
return;
}
for(int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (!socket.isClosed()){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String data = br.readLine();
if (data == null) continue;
out.println(data.toUpperCase());
}
else{
clients.remove(socket);
}
}
}
}
package entry;
import java.io.IOException;
import server.Server;
public class Main {
public static void main(String args[]) throws IOException{
Server server = new Server();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is the client :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[])throws IOException{
Socket socket = new Socket("192.168.0.110", 7575);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader sr = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream(), true);
while (true){
System.out.println("\n\nEnter a string : ");
String inp = br.readLine();
if (inp.equals("quit")) break;
pr.println(inp);
System.out.println("The response is : " + sr.readLine());
}
socket.close();
}
}
Strange thing here is when I set a breakpoint in the server code and step through the code in eclipse, the code is working exactly as expected i.e I am getting the response in the client.
But when I run it directly in eclipse, I am not getting the response in the client.
Cannot understand what is going wrong.
Edit
I seem to have fixed the issue.
Here is the code snippet :
Thread two = new Thread(){
public void run(){
try {
while (true){
Thread.sleep(1000); //This is the added line
work();
}
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
But I am still confused about what made the timing difference.
Is there any cleaner way to achieve this ?
I've solved the problem with a different approach.
Here is the new Approach:
ServerHandler.java :
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ServerHandler extends Thread{
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private ArrayList<Socket> clients;
public ServerHandler(Socket socket) throws IOException{
this.socket = socket;
clients = new ArrayList<Socket>();
if (!clients.contains(socket)){
clients.add(this.socket);
System.out.println(this.socket.getRemoteSocketAddress());
}
}
#Override
public void run(){
while (true){
if (clients.isEmpty()) break;
String str = null;
for (int i = 0; i < clients.size(); i++){
Socket socket = clients.get(i);
if (socket.isClosed()){
clients.remove(socket);
continue;
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
str = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(str.toUpperCase());
}
}
}
}
Main.java [for running the server] :
package entry;
import java.io.IOException;
import java.net.ServerSocket;
import server.ServerHandler;
public class Main {
public static void main(String args[]) throws IOException{
ServerSocket listener = new ServerSocket(7575);
try{
while (true){
new ServerHandler(listener.accept()).start();
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
listener.close();
}
}
}
Ok, Here we go.I don't understand the use of Arraylist for maintaining Connections unless You are handling the messy details for each Client.
The most used or prefered approach for handling multiple clients at a time can be understood in terms of an example:
Server.java
import java.net.ServerSocket;
import java.io.IOException;
class Server {
public static void main(String[] args) throws IOException {
try( ServerSocket ss = new ServerSocket(3333)) { // try with resources
new ServerThread(ss.accept()).start();
}
}
}
As you can see, I just defined a Class that will listen for Client connections, and as soon a request is made to the server it will start a Thread which is defined in the next class. A point to be noted here is the use of Try-with-Resources block. Any class that implements the Closeable interface can be enclosed within this try statement. The try-with-resources automatically handles closing of streams or connections for me. This means, you remove all your redundant try-catch blocks from your code and use this try instead.
Now,
ServerThread.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket s = null;
public ServerThread(Socket s) {
super("ServerThread");
this.s = s;
}
public void run() {
try( PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("In Server");
String in, out;
while ((in = stream.readLine()) != null) {
System.out.println("Msg 4m client: " + in);
if(in.equals("bye"))
break;
out = write.readLine();
pw.println(out);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Observe the try-with-resources statement over here, We can initialize multiple Connections/Input-Output Streams here, All of the opened connection will automatically be closed as soon as the compiler returns from try statement.Also, Observe the while statement, it will keep on running until the client is sending messages, and will quit if the message is "bye".
Finally, a Client program that sends request to the server.
Client.java
import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Client {
public static void main(String[] args) {
try( Socket s = new Socket("localhost", 3333);
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
BufferedReader stream = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader write = new BufferedReader(new InputStreamReader(System.in)) ) {
System.out.println("In Client");
String in;
while ((in = write.readLine()) != null) {
pw.println(in);
if(in.equals("bye"))
break;
System.out.println("Msg 4m server: " + stream.readLine());
}
} catch(IOException e) {
System.err.println("Exception: " + e);
}
}
}
Notice, the while Statement here, it will loop until the user is entering messages, and if the message is "bye", it will quit.Rest of the program can be easily understood from above explanation.

Print Socket Messages to Console in java

I am beginner to java and learning Socket Programming.I am using the basic chat server socket communication. I am having difficulty to print the server and client messages to the console window.
I would also implement this concept when i design my chat Server window UI and will update the char server intercommunication messages to my UI. I would like to know as how can I achieve that ?
Code for 1
Server.java
package ChApp;
import java.io.IOException;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Socket s;
ServerSocket server = new ServerSocket(3900);
while(true)
{
s = server.accept();
ServerHandl handle1 = new ServerHandl(s);
Thread t1= new Thread(handle1);
t1.start();
System.out.println("Connection Succesful...");
server.close();
}
}
}
Serverhandl.java
package ChApp;
import java.io.*;
import java.net.*;
public class ServerHandl implements Runnable {
Socket s= null;
BufferedReader read;
PrintWriter write;
String msg="Server is sending a sample msg";
public ServerHandl(Socket s)
{
this.s = s;
}
public void run()
{
try {
write = new PrintWriter(s.getOutputStream());
write.println(msg);
read = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(read.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
read.close();
write.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client.java
package ChApp;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket s= null;
BufferedReader read;
PrintWriter write = null;
String h;
StringBuilder sb = new StringBuilder();
String sendmsg="Reply from client";
s= new Socket("localhost",3900);
read = new BufferedReader(new InputStreamReader(s.getInputStream()));
while((h=read.readLine())!=null)
{
sb.append(h);
}
write = new PrintWriter(s.getOutputStream(),true);
write.write(sendmsg);
write.flush();
s.close();
read.close();
write.close();
}
}
Your client is calling readLine() until it returns null, but your server is reading from the connection so it hasn't closed it yet, so the null will never arrive, so you're deadlocked.
Read one line from the server and then send a response, then close the socket. Have the server close the socket after it calls readLine().

Socket in multithreading "deadlocked" Java

I am trying to launch server and client thread on the same process, but seems like the server thread is blocking the client thread (or vice versa). I'm not allowed to use any global variable between those threads(like semaphore or mutex, since the client and the server thread are launched by upper-class that I don't have the access of).
I found a similar question here , but it still use two different process (two main function).
Here is a sample of my code
The server code:
public class MyServer implements Runnable{
ServerSocket server;
Socket client;
PrintWriter out;
BufferedReader in;
public MyServer() throws IOException{
server = new ServerSocket(15243, 0, InetAddress.getByName("localhost"));
}
#Override
public void run() {
while(true){
try {
ArrayList<String> toSend = new ArrayList<String>();
System.out.println("I'll wait for the client");
client = server.accept();
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null){
toSend.add("answering : "+inputLine);
}
for(String resp : toSend){
out.println(resp);
}
client.close();
out.close();
in.close();
} catch (IOException ex) {
}
}
}
}
And the client code:
public class MyClient implements Runnable{
Socket socket;
PrintWriter out;
BufferedReader in;
public MyClient(){
}
#Override
public void run() {
int nbrTry = 0;
while(true){
try {
System.out.println("try number "+nbrTry);
socket = new Socket(InetAddress.getByName("localhost"), 15243);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello "+nbrTry+" !! ");
String inputLine;
while((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
nbrTry++;
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
}
}
And the supposed upper-class launching those thread:
public class TestIt {
public static void main(String[] argv) throws IOException{
MyServer server = new MyServer();
MyClient client = new MyClient();
(new Thread(server)).start();
(new Thread(client)).start();
}
}
It gives me as output:
I'll wait for the client
Try number 0
And it stuck here. What should I do to keep both server and client code running?
Thank you.
I'll be willing to take up your questions but basically you need to think through your logic a bit more carefully.
MyServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer implements Runnable {
ServerSocket server;
public MyServer() throws IOException {
server = new ServerSocket(15243, 0, InetAddress.getByName("localhost"));
}
#Override
public void run() {
while (true) {
try {
// Get a client.
Socket client = server.accept();
// Write to client to tell him you are waiting.
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("[Server] I'll wait for the client");
// Let user know something is happening.
System.out.println("[Server] I'll wait for the client");
// Read from client.
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String inputLine = in.readLine();
// Write answer back to client.
out.println("[Server] Answering : " + inputLine);
// Let user know what it sent to client.
System.out.println("[Server] Answering : " + inputLine);
in.close();
out.close();
client.close();
} catch (Exception e) {
}
}
}
}
MyClient.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyClient implements Runnable {
Socket socket;
PrintWriter out;
BufferedReader in;
public MyClient() throws UnknownHostException, IOException {
}
#Override
public void run() {
int nbrTry = 0;
while (true) {
try {
// Get a socket
socket = new Socket(InetAddress.getByName("localhost"), 15243);
// Wait till you can read from socket.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String inputLine = in.readLine();
//inputLine contains the text '[Server] I'll wait for the client'. means that server is waiting for us and we should respond.
// Write to socket
out = new PrintWriter(socket.getOutputStream(), true);
out.println("[Client] Hello " + nbrTry + " !! ");
// Let user know you wrote to socket
System.out.println("[Client] Hello " + nbrTry++ + " !! ");
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
}
}
TestIt.java
import java.io.IOException;
public class TestIt {
public static void main(String[] argv) throws IOException {
MyServer server = new MyServer();
MyClient client = new MyClient();
(new Thread(server)).start();
(new Thread(client)).start();
}
}
Your client sends a string, then reads until the stream is exhausted:
while((inputLine = in.readLine()) != null){
BufferedReader.readLine() only returns null at the end of the stream, as I recall. On a stream, it will block until input is available
Your server receives until the stream is exhausted, then sends back its response.
After sending one line, you now have:
Your client waiting for a response.
Your server still waiting for more data from the client. But it doesn't send anything back until the end of the stream from the client (which never happens because the client is waiting for your response).

How do I send a message over multiple threads in Java?

I made a simple chat server and client and the client will send text to the server, and the server will only send it back to the client that sent it to it. I want it to send to all the clients instead of just that one.
Server:
import java.io.IOException;
import java.net.ServerSocket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket s = null;
boolean listening = true;
try {
s = new ServerSocket(5555);
} catch (IOException e) {
e.printStackTrace();
}
while(listening)
new ServerThread(s.accept()).start();
}
}
Thread:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket sock = null;
public ServerThread(Socket socket) {
super("Server Thread.");
this.sock = socket;
}
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
System.out.println(sock.getInetAddress() + " has joined.");
out = new PrintWriter(sock.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String input;
while((input = in.readLine()) != null) {
System.out.println(input);
out.println(input);
}
in.close();
out.close();
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
public static void main(String[] args) throws IOException {
Socket sock = null;
PrintWriter out = null;
BufferedReader in = null;
try {
sock = new Socket("127.0.0.1", 5555);
out = new PrintWriter(sock.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
out.close();
in.close();
sock.close();
}
}
Have your server keep List<ServerThread>. Have a void sendAll(String) method on the Server that can be accessed by the ServerThreads and when they get information, that sendAll() method tells each ServerThread to send out their information.
What you're looking at doing though will require some asynchronous work (and is most certainly not trivial!)
Well, briefly: you're creating those ServerThreads and starting them, but you're not keeping track of them in any way. Imagine if each time you created one, you put it in a HashSet. Then each time a client sent a String, you iterated over the Set and sent the String to each of the clients. A method sendMessage(String) in ServerThread would make this easier, of course.
Change your client to have one thread for reading from the server plus one thread for reading from the keyboard.
Create a function which allows server socket threads to communicate with each other and use synchronization so that only one thread is writing to each outputstream at one time. So in brief, create a list of server threads which is shared by all threads and move your PrintWriter into a field with a getter, so it can be accessed from outside.
glowcoder and Ernest Friedman-Hill seem to be giving good advice, but I wanted to add one thing: have you considered using the Observer pattern and java's default implementation of Observable?
The Server could extend the Observable object, and the ServerThread could implement the Observer interface. As you create new ServerThreads, register them with the Observable using
server.addObserver(serverThread);
The ServerThread will need to know about the Server it is linked to.
Then whenever a client sends in a new message, instead of out.println(userInput) do the following:
synchronized (server) {
server.setChanged();
server.notifyObservers(userInput);
}
You also need to implement ServerThread.update(Observable o, Object update), in which you would get the serverThread's socket's output stream and write ((String) update) to it.
Note that this will use one thread to send messages to all the observers and will block other threads from processing their chats until it has sent to all observers.

Categories

Resources