I have a program ready that acts as a client and another that acts as a server.
I want to be able to send a message to the server, and the server will then forward the message to another client that is also connected to the server.
So the the server is supposed to forward the message to the other client.
How would i be able to do that, and what do I need to read up on?
This is what i got now.
Server.java
package server;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server{
public static void run() {
ServerSocket serverSocket = null;
Socket socket = null;
try{
while(true){
serverSocket = new ServerSocket(5555);
socket = serverSocket.accept();
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String message = bufferedReader.readLine();
System.out.println(message);
if(message != null){
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println("Message receivd!");
}
streamReader.close();
socket.close();
serverSocket.close();
bufferedReader.close();
}
}catch(Exception e){}
// try{
//
// }catch(Exception e){}
}
public static void main(String[]args){
Server s = new Server();
s.run();
}
}
And then I also got TCPClient.java
package client;
import java.net.*;
import java.io.*;
public class TCPClient {
private String serverIP = "localhost";
private int serverPort = 1111;
private int count = 0;
private Thread thread;
public TCPClient() {
this.thread = new Thread(new ConnectAndListenToServer());
// thread.start();
}
public void sendMessage(int count){
this.count = count;
this.thread = new Thread(new ConnectAndListenToServer());
thread.start();
}
private class ConnectAndListenToServer implements Runnable {
Socket socket = null;
public void run() {
BufferedReader bufferedReader = null;
InputStreamReader streamReader = null;
try {
socket = new Socket(serverIP,serverPort);
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println(count);
streamReader = new InputStreamReader(socket.getInputStream());
bufferedReader = new BufferedReader(streamReader);
String message = bufferedReader.readLine();
if(message != null){
System.out.println(message);
}
}catch(Exception e){}
try{
socket.close();
bufferedReader.close();
streamReader.close();
}catch(Exception ee){}
}
}
}
How would i be able to forward the messeage already received on the server to another client?