如何通过Socket读取/写入2d char数组?

时间:2015-11-24 19:40:11

标签: java arrays sockets io char

所以我正在写一个LAN tic-tac-toe游戏。我有"板"存储为2维char数组。我希望能够通过套接字发送和接收此数组。我目前正在使用InputStreamOutputStream来发送单个字节。但是,我不认为这适用于发送阵列。此外,这些流似乎只能发送int类型的数据。有人可以向我解释如何使用I / O流在套接字上发送2维char数组。示例代码会很棒!谢谢。

当前代码:

public void communicate() {
    try {
        OutputStream os = client.getOutputStream();
        InputStream is = client.getInputStream();
    }

    while (gameOver == false) {
        char[][] board = new char[3][3];
        try {
            os.write(board); //this dosen't work, only sends non-array int types. 
        } catch (IOException e) {

            e.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:1)

Java InputStreamOutputStream类只处理读写byte(s)。您当然可以使用输入和输出流将字符数组写为字节。

public static char[][] readBoard(InputStream in) throws IOException {
    char[][] board = new char[3][3];
    for(int i=0;i<9;i++) {
        board[i/3][i%3] = (char) in.read();
    }
    return board;
}

public static void writeBoard(OutputStream out, char[][] board) throws IOException {
    for(int i=0;i<9;i++) {
        out.write(board[i/3][i%3]);
    }
}

您还可以使用ObjectOutputStreamObjectInputStream来通过流读取和写入对象。请注意,读取和写入这些流的类必须实现Serializable接口(您的char[][]将起作用)。

public static char[][] readBoard(InputStream in) throws IOException {
    ObjectInputStream ois = new ObjectInputStream(in);
    return (char[][]) ois.readObject();
}

public static void writeBoard(OutputStream out, char[][] board) throws IOException {
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(board);
}