I’m trying to create a simple chat program in java, using a frame. The user can either host a server (by clicking the server button) or connect as a client (using the connect button). the problem I’m having is the server button. My goal is that when the Start server button is clicked, all of the other buttons and fields are disabled, and the startServer method should run.
The entire program is inside of a while (!kill) loop, and right now, it’s just checking the isServer boolean.
while (!kill)
{
if (isServer)
{
startServer();
}
}
isServer is set to true inside of actionPerformed when the startServerButton is pressed.
my problem is that startServer() is never run because the while (!kill) loop isn’t getting the updated isServer value when startServerButton is clicked.
Here’s my run method:
public void run()
{
conversationBox.appendText("Session Start.\n");
inputBox.requestFocus();
while (!kill)
{
if (isServer)
{
startServer();
}
}
}
and here’s my actionPerformed:
public void actionPerformed(ActionEvent e) throws NumberFormatException
{
Object o = e.getSource();
if (o == sendButton || o == inputBox)
{
if(inputBox.getText() != "")
{
clientSendMsg = inputBox.getText();
inputBox.setText("");
}
}
if (o == changeHost || o == hostField)
{
if (hostField.getText() != "" && hostField.getText() != host)
{
host = hostField.getText();
conversationBox.appendText("Host changed to " + host + "\n");
}
}
if (o == changePort || o == portField)
{
if (portField.getText() != "" && Integer.valueOf(portField.getText()) != port)
{
try
{
port = Integer.valueOf(portField.getText());
conversationBox.appendText("Port changed to " + port + "\n");
}
catch(NumberFormatException up)
{
throw up; //blargh enter a real value
}
}
}
if (o == startServerButton)
{
isServer = true;
startServerButton.enable(false);
connectButton.enable(false);
changeHost.enable(false);
changePort.enable(false);
sendButton.enable(false);
hostField.enable(false);
portField.enable(false);
inputBox.enable(false);
}
inputBox.requestFocus();
}
Obviously, the program is nowhere near complete, but this is a pretty big hurdle to ignore, so I figured it would be best to get it fixed before chugging along. Also, it should be noted that I have a new Thread(this).start(); inside the Chat() object that creates the frame layout. I’m not 100% sure how effective this is.
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable.
Here is a link:
Explanation about volatile