Can anyone help with this code please?
This is just the Server side code but it isn't working properly.
In ChatServerGUI ...
* when I click 'Connect' button (connectBtnActionPerformed) it works fine, but when I click 'Send' button (sendMsgActionPerformed) I get a null pointer exception due to ChatServer being null.
* run() is called via 'Connect' which does chatServ = new ChatServer(...) & that has a while(true) loop in it. It never finishes the constructor due to this & when I try to use the class variable chatServ in 'Send' it is not set.
Any help/ideas appreciated please!
Full server side code is here:
https://www.dropbox.com/.../AACUBfxbUvhXw8vsaViB73nha
-----------
CHATSERVER
-----------
<code>
// import relevant libraries
import java.io.*; // InetAddress, Socket, ServerSocket, etc
import java.net.*; // BufferedReader, PrintWriter, etc
import java.util.*; // Vector
public class ChatServer {
// class variables
private ServerSocket servSock = null;
private Socket cliSock = null;
private ChatServerGUI servGUI = null;
private int portNum;
ChatServerThread servThread = null;
private Vector<ChatServerThread> vServThreads = new Vector<ChatServerThread>(2,2);
private boolean stayConnected = false;
/*
* constructor method - create a ChatServer object
*/
public ChatServer( ChatServerGUI _servGUI, int _portNum ) {
PrintWriter writeOut = null;
stayConnected = true;
try {
// check the parameters passed are valid
if ( _servGUI == null || _portNum <= 1024 )
return;
// set class variables
servGUI = _servGUI;
portNum = _portNum;
// listen for client connections on the given port #
servSock = new ServerSocket( portNum );
servGUI.appendMessage( "Waiting for client connections on port " + portNum + "." );
while ( stayConnected ) {
// wait for a client connection, then accept it
cliSock = servSock.accept();
servGUI.appendMessage( "Client " + cliSock.getInetAddress()
+ " has connected on port " + cliSock.getLocalPort() );
// create a stream so we can write to the connected client
writeOut = new PrintWriter( new OutputStreamWriter( cliSock.getOutputStream() ) );
writeOut.print( "You are now connected to the server on port " + _portNum + "." );
writeOut.flush();
// create a thread to handle the rest, add it to the vector & start running it
servThread = new ChatServerThread( this );
vServThreads.add(servThread);
servThread.start();
}
// close any open sockets/streams
if ( writeOut != null ) writeOut.close();
this.close();
}
catch( IOException ioe ) {
System.out.println( "Error: " + ioe );
}
}
/*
* showMessage method - show the message in the server GUI
*/
public void showMessage ( String _msgStr ) {
servGUI.appendMessage( _msgStr );
}
/*
* broadcastMessage method - send the message to every client connected
*/
public void broadcastMessage ( String _msgStr ) {
// confirm the message is not empty and there are clients connected
if ( _msgStr.isEmpty() || vServThreads.size() == 0 )
return;
// loop backwards due to the 'remove' function being used
for( int i = vServThreads.size(); i >= 0; i-- ) {
ChatServerThread tempServThr = vServThreads.get( i );
// send message to the client, if it fails remove from vector
if ( !tempServThr.broadcastMessage( _msgStr ) ) {
vServThreads.remove( i );
showMessage( "A client disconnected." );
}
}
}
/*
* getServSocket method - return the class's ServerSocket
*/
public ServerSocket getServSocket() {
return servSock;
}
/*
* getCliSocket method - return the class's Socket
*/
public Socket getCliSocket() {
return cliSock;
}
/*
* close method - close any open connections (sockets/streams)
*/
public void close() {
stayConnected = false;
ChatServerThread tempServThread = null;
for ( int i = 0; i <= vServThreads.size(); i++ ) {
tempServThread = (ChatServerThread) vServThreads.get(i);
tempServThread.close();
}
tempServThread.close();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ChatServerGUI servGUI = null;
ChatServer chatServ = null;
// check the required number of arguments have been supplied, otherwise exit
if ( args.length == 1 ) {
servGUI = new ChatServerGUI();
chatServ = new ChatServer( servGUI, Integer.parseInt(args[0]) );
}
else {
System.out.println(" USAGE: java ChatClient <OptionalServerHostNameOrIpAddress>" );
System.exit(0);
}
}
}
</code>
-----------
CHATSERVERTHREAD
-----------
<code>
public class ChatServerThread extends Thread {
// class variables
ChatServer chatServ = null;
BufferedReader readIn = null;
PrintWriter writeOut = null;
private boolean stayConnected = false;
/*
* constructor method - create a ChatServerThread object
*/
ChatServerThread( ChatServer _chatServ ) {
chatServ = _chatServ;
}
/*
* broadcastMessage method - send the message to the client
*/
public boolean broadcastMessage( String _msgStr ) {
Socket cliSock = chatServ.getCliSocket();
stayConnected = cliSock.isConnected();
if ( !stayConnected ) {
this.close();
return false;
}
// send the message to the client
writeOut.println( _msgStr );
writeOut.flush();
return true;
}
/*
* run method - read in any data from the client & display it
*/
public void run() {
try {
String msgLine = null;
stayConnected = chatServ.getCliSocket().isConnected();
while ( stayConnected ) {
// read from the socket
msgLine = readIn.readLine();
// check the line is not empty
if ( ! msgLine.isEmpty() ) {
// display line to server
chatServ.showMessage( "Sent: " + msgLine );
// display line to client
writeOut.println( msgLine );
writeOut.flush();
}
}
// close the connections
this.close();
}
catch ( IOException ioe ) {
System.out.println( "Error: " + ioe );
}
catch ( NullPointerException npe ) {
System.out.println( "Error: " + npe );
}
}
/*
* close method - close any open connections (sockets/streams)
*/
public void close() {
try {
stayConnected = false;
// close any open sockets/streams
if ( readIn != null ) readIn.close();
if ( writeOut != null ) writeOut.close();
chatServ.close();
}
catch ( IOException ioe ) {
// do nothing
}
}
}
</code>
-----------
CHATSERVERTHREAD
-----------
// import relevant libraries
import java.awt.event.*;
public class ChatServerGUI extends javax.swing.JFrame implements Runnable {
// class variables
private ChatServer chatServ = null;
private Thread thread = null;
/*
* constructor method - create a ChatServerGUI object
*/
public ChatServerGUI() {
initComponents();
}
private void initComponents() {
*** lots of IDE code was here ***
}
/*
* sendMsgActionPerformed method - broadcast the typed message to the clients
*/
private void sendMsgActionPerformed(java.awt.event.ActionEvent evt) {
String msgStr = msgField.getText();
// check that msgField contains text
if ( msgStr.isEmpty() || msgStr.trim().isEmpty() )
return;
// add the msgField contents to the outputArea
outputArea.append(msgStr + "\n");
// remove contents of msgField
msgField.setText("");
System.out.println("ChatServerGUI about to send: " + msgStr);
System.out.println("chatServ: " + chatServ);
if ( chatServ == null ) {
System.out.println("WARNING chatServ IS NULL");
return;
}
chatServ.broadcastMessage( "SERVER: " + msgStr + "\n" );
}
/*
* windowClosing method - exit the application if the user clicks the X button (top corner)
*/
public void windowClosing( WindowEvent we ) {
System.exit(0);
}
/*
* exitActionPerformed method - exit the application
*/
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
/*
* connectBtnActionPerformed method - create a connection & wait for clients to connect
*/
private void connectBtnActionPerformed(java.awt.event.ActionEvent evt) {
// user pressed "Disconnect"
if ( connectBtn.getText() == "Disconnect" ) {
connectBtn.setText( "Connect" );
}
// user pressed "Connect"
else {
connectBtn.setText( "Disconnect" );
thread = new Thread(this);
thread.start();
}
}
/*
* appendMessage method - append the message to the output text area
*/
public void appendMessage( String _msgStr ) {
if ( !_msgStr.isEmpty() && !_msgStr.trim().isEmpty() ) {
// add the msgField contents to the outputArea
outputArea.append(_msgStr + "\n");
}
}
/*
* run method - create a ChatServer object
*/
public void run() {
chatServ = new ChatServer( this, 2222 );
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
*** lots of IDE code was here ***
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ChatServerGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel bottomPanel;
private javax.swing.JButton connectBtn;
private javax.swing.JButton exit;
private javax.swing.JTextField msgField;
private javax.swing.JPanel msgPanel;
private javax.swing.JTextArea outputArea;
private javax.swing.JPanel outputPanel;
private javax.swing.JButton sendMsg;
// End of variables declaration
}
</code>