views:

118

answers:

2

For some reason my server stops running in the marked area of my code, and I can't figure out why.

import java.net.*;
import java.io.*;

public class SlickServer{
    public static void main(String[] args) throws IOException {

        int MAX_PLAYERS = 3;
        int playerNum = 0;
        Player[] players = new Player[MAX_PLAYERS];
        players[0] = new Player(25,25);
        players[1] = new Player(125,125);
        players[2] = new Player(225,225);
        ServerSocket serverSocket = new ServerSocket(40);
        boolean listening = true;

        while(listening){
            System.out.println("Waiting to connect with: " + playerNum);
            new ClientThread(serverSocket.accept(), players, playerNum).start();
            //stops here.
            System.out.println("Connected with: " + playerNum + " Now incrementing");
            playerNum++;
            System.out.println("Incremented to: " + playerNum);
        }



        serverSocket.close();
        System.exit(0);
    }
}

And here is the thread:

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.io.*;

public class ClientThread extends Thread implements Runnable{
    Socket acceptedSocket;
    Player[] players;
    int playerNum;

    public ClientThread(Socket acceptedSocket, Player[] players, int playerNum){
     super("ClientThread");
     this.acceptedSocket = acceptedSocket;
     this.players = players;
     this.playerNum = playerNum;
    }

    public void run(){
     try{

      Socket clientSocket = acceptedSocket;
      System.out.println("Accepted. Now creating I/O.");
      ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
            System.out.println("I/O with: " + playerNum + " working.");
            out.writeInt(playerNum);
            out.flush();
     }

     catch(Exception e){
      e.printStackTrace();
      System.exit(1);
     }


    }

    public void start(){
     run();
    }

}
A: 

Does it crash? If you wrap a try/catch around the new ClientThread(...) line, do you get an exception?

Seth
Nope, no crash.
William
+8  A: 

The code in your "client thread" is actually running on your main thread.

That's because you've written your own implementation of start that doesn't actually spawn a new thread.

You don't want to do that.

Anon.
That fixed it, thank you ^_^
William