通过套接字同时发送和接收数据

时间:2016-05-05 01:08:05

标签: java sockets tcp

我正在研究一种在客户端和服务器之间发送位置数据的小游戏,以了解套接字如何工作。

服务器可以发送和接收数据没问题,客户端可以发送数据,但是当客户端尝试从服务器读入数据时,程序会挂起。 (这部分已被注释掉)

服务器代码:

public void run() {

    try {
        serverSocket = new ServerSocket(10007);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 10007.");
        System.exit(1);
    }

    try {
        System.out.println("Waiting for connection...");
        clientSocket = serverSocket.accept();
    } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
    }
    System.out.println("Connection successful");
    System.out.println("Waiting for input.....");
    while (true) {
        try {
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            if (in.readLine() != "0" && in.readLine() != null) {
                setXY(in.readLine());
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        out.println("X" + Graphics.charX);
        out.println("Y" + Graphics.charY);
    }

客户代码:

public void run() {

    try {
        System.out.println("Attemping to connect to host " + serverHostname + " on port " + serverPort + ".");
        echoSocket = new Socket(serverHostname, serverPort);
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: " + serverHostname);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
        System.exit(1);
    }
    while (true) {

        try {
            in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            /*if (in.readLine() != "0" && in.readLine() != null) {
                setXY(in.readLine());
            }*/
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        out.println("X" + Graphics.charX);
        out.println("Y" + Graphics.charY);

    }

}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

你需要两个线程同时读/写阻塞套接字(这是你要做的)。当您调用in.readLine()时,当前线程将阻塞,直到收到一行数据。