0

是的,我确实看过 sun 上的教程,但它们对我没有帮助,只传输了第一个命令。

我有一个方法

public void openConnection() throws IOException{

    serverSocket = new ServerSocket(5346);

    Socket simSocket = serverSocket.accept();

    is = simSocket.getInputStream();
    os = simSocket.getOutputStream();

    writer = new PrintWriter(os);
    isReader = new InputStreamReader(is);
    reader = new BufferedReader(isReader);

    System.out.println("Connection succesfull.");
}

public void sendTo(int command) {
    try {
        writer.println(command);
        writer.flush();
    } catch(Exception e) {
        System.out.println("Error sending command to the robot");
        System.out.println(e.toString());
    }
}

在发送方,并且

public static void setUpConnection() {
    try {
        socket = new Socket(InetAddress.getLocalHost(), 5346);
        is = new InputStreamReader(
                socket.getInputStream());
        reader = new BufferedReader(is);
        writer = new PrintWriter(socket.getOutputStream());
        System.out.println("Simulator: connection succesful");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

while (true) {
                intCommand = reader.read();
                ett = reader.readLine(); // does nothing, but without this line it doesn't work
                command = (char) intCommand;

在接收端。它可以完美地发送一个字符或一个字符的ASCII码。我需要更改此代码以发送整数或仅发送字节数组而不是字符。如果我只留下 InputStream 和 OutputStream 它确实接收到第一个命令,仅此而已,而这些方法不断接收通过 sendTo 发送的内容。即使在套接字文档中,它们也只有发送字符的示例。

4

1 回答 1

0

只需对您的服务器进行编码以将接收到的值存储为 int 而不是 char。

于 2012-01-26T16:15:47.310 回答