由于某种原因,我的服务器停止在我的代码的标记区域中运行,我无法弄清楚原因。
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);
}
}
以下是主题:
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();
}
}
答案 0 :(得分:8)
“客户端线程”中的代码实际上正在主线程上运行。
那是因为你编写了自己的start
实现,它实际上并没有产生新的线程。
你不想这样做。