【问题标题】:How to transfer integer or byte array through socket in javajava中如何通过socket传输整数或字节数组
【发布时间】:2012-02-19 17:27:47
【问题描述】:

是的,我确实看过 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 发送的内容。即使在套接字文档中,它们也只有发送字符的示例。

【问题讨论】:

  • 研究序列化(创建一个实现可序列化的类或使用可用的序列化 API 之一)。

标签: java sockets inputstream bufferedreader bufferedinputstream


【解决方案1】:

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

【讨论】:

  • 我该怎么做,我认为只是使用什么样的 InputStream 或 smth 的问题,因为它完美地发送数字,只需要将它作为字节数组接收而不尝试从中获取一个字符
  • 如果问题出在接收方,那么只需确保接收方知道流中的内容,以便将其存储为正确的数据类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
相关资源
最近更新 更多