gpt4 book ai didi

使用objectinputstream和objectoutputstream的java网络

转载 作者:行者123 更新时间:2023-12-02 11:17:42 24 4
gpt4 key购买 nike

我制作了 2 个小型控制台应用程序(服务器和客户端)来学习如何让服务器和客户端使用 objectInputStream 和 objectOutputStream 相互发送多个变量值。然而,当我要求我的客户端程序创建 objectInputStream 对象时,它似乎陷入了困境。这是我的代码:

public class client {

static String key, temp, tester;
static UserInfo ui = new UserInfo();

public static void main(String[]args) throws UnknownHostException, IOException, ClassNotFoundException {
//CONNECT TO SERVER
Scanner scanner = new Scanner(System.in);
Socket socket = new Socket("127.0.0.1", 1350);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());

//INPUT
System.out.println("Client:" + "Enter a message!");
ui.message = scanner.nextLine();
System.out.println("Client:" + "Enter a number!");
ui.number = scanner.nextInt();

//WRITE & SEND
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(ui);
oos.flush();

//RECEIVE AND READ
UserInfo info = (UserInfo) ois.readObject();

System.out.println("Server:" + info);
}

}

这是我的服务器代码:

public class ser {

static String key, temp;
static UserInfo ui = new UserInfo();

public static void main(String[]args) throws IOException, ClassNotFoundException {
ServerSocket s1 = new ServerSocket(1350);
System.out.println("Server started.");
Socket soc = s1.accept();

ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
UserInfo info = (UserInfo) ois.readObject();

info.message += ", and this is the server's message-part";
info.number *= 3;

oos.writeObject(ui);
oos.flush();
}

}

public class UserInfo implements Serializable{
public int number;
public String message;
}

需要明确的是:我没有收到任何错误,它只是在到达 objectinputstream 时停止。我使用对象输入/输出流类是错误的吗?我还听说过一些关于数据输出/输入流的事情。这是我应该尝试的吗?

编辑:使用这个新编辑的代码,它不再卡住或死锁,但我收到此异常错误,告诉我它不知道来源:

Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at cli.main(cli.java:33)

最佳答案

it just stops the moment it reaches the objectoutputstream

不,没有。它在到达 new ObjectInputStream(...) 时停止。

您必须先创建ObjectOutputStream,然后再创建ObjectInputStream。否则,您会在尝试读取流 header 时陷入僵局。

关于使用objectinputstream和objectoutputstream的java网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164135/

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