如何在java中通过socket传递整数或字节数组

时间:2012-01-26 16:11:36

标签: java sockets inputstream bufferedreader bufferedinputstream

是的,我确实看过关于太阳的教程,他们在我的情况下没有帮助,只转移了第一个命令。

我有一个方法

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;

在接收方。它完美地发送char或ascii数字的char。我需要的是更改此代码以发送整数或简单的字节数组而不是char。如果我只是简单地离开InputStream和OutputStream它确实接收到第一个命令就是这样,而这些方法不断接收通过sendTo发送的内容。即使在套接字文档中,它们也只有发送字符的例外。

1 个答案:

答案 0 :(得分:0)

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