I'm developing a chat application, and I'm using global variables as a way to allow server threads to access and update shared information (I know this isn't recommended, but I'm going to stick with this method for the time being).
What I want to happen, is that every time a new message is submitted, it prints to all the clients so that all the clients can see them.
What actually happens, is that it only updates the client that I've submitted a message with. Though it does kinda of receive messages from the other client. It's not simultaneous.
Where am I going wrong?
class Server {
public static void main(String argv[]) throws Exception {
boolean listening = true;
int portNumber = 6000;
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
while (listening) {
new ServerThread(serverSocket.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + portNumber);
System.exit(-1);
}
}
}
Server thread for handling clients.
public class ServerThread extends Thread {
private Socket socket = null;
public ServerThread(Socket socket) {
super("ServerThread");
this.socket = socket;
}
public void run () {
int msgCnt = 0;
boolean running = true;
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
) {
String inputLine, outputLine;
while(running) {
while ((inputLine = in.readLine()) != null) {
if (Global.messageCount > msgCnt){
out.println(Global.currentMessage + " received from others");
msgCnt = msgCnt + 1;
}
outputLine = inputLine;
Global.currentMessage = inputLine;
Global.messageCount = Global.messageCount + 1;
//out.println(outputLine);
}
//if (outputLine.equals("QUIT"))
// break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Also, client code
class Client {
public static void main(String argv[]) throws Exception {
String sentMessage; //variable for input
String status;
boolean running;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6000); //name of computer to connect with and port number to use
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
running = true;
while(running)
{
sentMessage = inFromUser.readLine(); //user inputs text to variable 'sentMessage'
outToServer.writeBytes(sentMessage + '\n'); //the variable is sent to the server
status = inFromServer.readLine(); //the modified data is returned from the server
System.out.println("FROM SERVER: " + status); //display to user
}
clientSocket.close();
}
}
Global class, just a few variables
public class Global {
public static String currentMessage = "Nothing";
public static int messageCount = 0;
}