Java Socket ArrayList NullPointer Exception
pWhenever I run my Chat Server it works until the client connects and then
I get a Null Pointer exception at connections.add(socket); which crashes
it and then this happens every time I run it. I know my client side is
fine because I watched a tutorial a few months ago on how to do this and
that server works with my client without crashing/p precodeprivate static
ServerSocket server; private static Socket socket; private static Scanner
input; private static PrintWriter output; private static final int port =
444; private static String message; private static ArrayListlt;Socketgt;
connections; private static Server serverClass; public Server() { message
= ; connections = new ArrayListlt;Socketgt;(); serverClass = new Server();
} public void run() { try { try { input = new
Scanner(socket.getInputStream()); output = new
PrintWriter(socket.getOutputStream()); while(true) { checkConnection();
if(!input.hasNext()) { return; } message = input.nextLine();
System.out.println(Client said: + message); for(int i = 1; i lt;=
connections.size(); i++) { Socket tempSock = (Socket) connections.get(i -
1); output.println(message); output.flush(); } } } finally {
socket.close(); } } catch(Exception e) { System.out.print(e); } } public
void checkConnection() throws IOException { if(!socket.isConnected()) {
for(int i = 1; i lt;= connections.size(); i++) { if(connections.get(i) ==
socket) { connections.remove(i); } } for(int i = 1; i lt;=
connections.size(); i++) { Socket disconnectedUser = (Socket)
connections.get(i - 1); System.out.println(disconnectedUser + has
Disconnected!); } } } public static void main(String[] args) throws
IOException{ try { server = new ServerSocket(port);
System.out.println(Waiting for Clients... ); while(true) { socket =
server.accept(); connections.add(socket); System.out.println(Client
connected from: + socket.getLocalAddress().getHostName()); Thread thread =
new Thread(serverClass); thread.start(); } } catch(Exception e) {
e.printStackTrace(); } } /code/pre
No comments:
Post a Comment