gpt4 book ai didi

java - 如何通过套接字读取/写入二维字符数组?

转载 作者:行者123 更新时间:2023-12-01 10:51:03 28 4
gpt4 key购买 nike

所以我正在编写一个 LAN tic-tac-toe 游戏。我将“board”存储为二维 char 数组。我希望能够通过套接字发送和接收这个数组。我目前正在使用 InputStreamOutputStream 发送单个字节。但是,我认为这不适用于发送数组。此外,这些流似乎只能发送 int 类型数据。有人可以向我解释一下如何使用 I/O 流通过套接字发送二维 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();
}

}
}

最佳答案

Java InputStreamOutputStream 类仅处理读取和写入字节。您当然可以仅使用输入和输出流将字符数组写为字节。

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通过流读取和写入对象。请注意,读取和写入这些流的类必须实现 Serialized 接口(interface)(您的 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);
}

关于java - 如何通过套接字读取/写入二维字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33902371/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com