Java TCP连接套接字不写入输出流

时间:2018-03-31 08:16:01

标签: java tcp

我正在为一个用java编码的游戏编写服务器。由于某种原因,输出流实际上不会将信息发送回客户端。我已经尝试了所有的东西,但是关闭套接字最终会导致程序错误,因为套接字在写入输出流之前已关闭。我无法弄明白为什么。

编辑:我在这个gist中添加了很多代码。此外,为了澄清,即使我没有关闭套接字,响应也根本没有发送。客户只是在等待答案,而不是收到答案。

这是我的代码。

public class ServerThread extends Thread {

private Socket clientSocket;
private List<Player> players;
public Player player = null;

public ServerThread (Socket clientSocket, List<Player> players)
{
    this.clientSocket = clientSocket;
    this.players = players;
}

public void run()
{
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        DataOutputStream os = new DataOutputStream(clientSocket.getOutputStream());

        String req = br.readLine();
        br.close();
        String response = buildResponse(req);

        os.writeBytes(response);
        os.flush();
        System.out.println("Sending [ " + response + " ] to " + clientSocket.getInetAddress().getHostAddress());

        player = addPlayerFromRequest(req);
    } catch (IOException ex) {
        Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
    } 

    try {
        clientSocket.close();
    } catch (IOException ex) {
        Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public String buildResponse(String req)
{
    List<Player> plays;
    plays = players;

    String name = req.split(",")[0];

    String response = "";

    if (plays.size() <= 1) {
        return response;
    }

    for (int i = 0; i < plays.size(); i++) {
        Player p = plays.get(i);
        if (!p.name.equals(name)) {
            response += p.name + "," + p.x + "," + p.y + "," + p.z + "," + p.rx + "," + p.rx + "," + p.rz + ";";
        }
    }
    return response;
}

public Player addPlayerFromRequest (String req)
{
    String[] list = req.split(",");
    String user = list[0];
    float x = Float.parseFloat(list[1]);
    float y = Float.parseFloat(list[2]);
    float z = Float.parseFloat(list[3]);
    float rx = Float.parseFloat(list[4]);
    float ry = Float.parseFloat(list[5]);
    float rz = Float.parseFloat(list[6]);

    return new Player(x, y, z, rx, ry, rz, user);
}
}

1 个答案:

答案 0 :(得分:0)

由于SocketException: Socket closed,此代码会抛出br.close(),但假设您已将其删除,我建议您的客户正在阅读行,但您不会发送行。在邮件中添加行终止符,或使用BufferedWriter.newLine()