【问题标题】:Send and Receive data Simultaneously via Sockets通过 Socket 同时发送和接收数据
【发布时间】:2016-05-05 01:08:05
【问题描述】:

我正在开发一个在客户端和服务器之间发送位置数据的小游戏,以了解 Socket 的工作原理。

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

服务器代码:

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

    }

}

非常感谢任何帮助!

【问题讨论】:

  • 你在这里做线程吗?
  • 是的,这个类是一个线程。
  • 嗯,你的线程不正确,一点也不,你会想看看如何用线程来做到这一点。这类问题已经问了很多次了,所以做一些搜索——如果你这样做了,你会得到回报的。
  • 谢谢。线程绝对是问题所在。我正在重写它以将其拆分为 2 个线程:读取和写入。问题是调用in.readLine()时线程挂了,所以需要拆分成两个线程。

标签: java sockets tcp


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2023-04-11
    • 2014-10-27
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多