【问题标题】:My java server stops in the middle of its code我的 java 服务器在其代码中间停止
【发布时间】:2009-12-17 22:17:57
【问题描述】:

由于某种原因,我的服务器在代码的标记区域停止运行,我不知道为什么。

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();
    }

}

【问题讨论】:

  • 它会崩溃吗?如果在 new ClientThread(...) 行周围加上 try/catch,会出现异常吗?
  • 这不是您的问题的答案,只是一个评论。如果您编写自己的服务器只是为了了解如何做,请继续。如果您想完成某件事,您可能需要考虑这样的事情:jboss.org/netty

标签: java client client-server


【解决方案1】:

您的“客户端线程”中的代码实际上是在您的主线程上运行的。

这是因为您已经编写了自己的 start 实现,但实际上并没有产生新线程。

你不想那样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多