gpt4 book ai didi

java - 服务器仅读取从客户端发送的第一个对象

转载 作者:行者123 更新时间:2023-12-01 14:55:26 25 4
gpt4 key购买 nike

我在将对象发送到服务器时遇到问题。现在,我已经设置了服务器并监听客户端。客户端连接,发送一个测试对象(只是一个字符串)并将其输出到命令行。它适用于发送的第一个字符串,但此后则无效。

服务器(Hivemind.java):

    // Open server socket for listening
ServerSocket ss = null;
boolean listening = true;
try {
ss = new ServerSocket(PORT_NUMBER);
} catch (IOException e) {
System.err.println("Cannot start listening on port " + PORT_NUMBER);
e.printStackTrace();
}

// While listening is true, listen for new clients
while (listening) {
Socket socket = ss.accept();
ServerDispatcher dispatcher = new ServerDispatcher(socket);
dispatcher.start();
}

// Close the socket after we are done listening
ss.close();

服务器线程(ServerDispatcher):

public ServerDispatcher(Socket socket) {
super("ServerDispatcher");
this.socket = socket;
}

public void run() {
System.out.println("Client connected");
try {
input = socket.getInputStream();
objInput = new ObjectInputStream(input);
Object obj = null;

try {
obj = (String)objInput.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
}

System.out.println(obj);
} catch (IOException ex) {
Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
}

连接类(HivemindConnect.java):

public HivemindConnect(int port) {
this.port = port;
url = "localhost";
}

public HivemindConnect(int port, String url) {
this.port = port;
this.url = url;
}

public void connect() {
try {
socket = new Socket(url, port);
output = socket.getOutputStream();
objOutput = new ObjectOutputStream(output);
} catch (IOException e) {
e.printStackTrace();
}
}

public void close() {
try {
objOutput.close();
output.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void send(Object obj) {
try {
objOutput.writeObject(obj);
objOutput.flush();
} catch (IOException ex) {
Logger.getLogger(HivemindConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}

客户顶部组件:

// When the TC is opened connect to the server
@Override
public void componentOpened() {
hivemind = new HivemindConnect(9001);
hivemind.connect();
}

private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
hivemind.send(txtText.getText());
}

// When the TC is closed close the connection to the server
@Override
public void componentClosed() {
hivemind.close();
}

最佳答案

你需要一个像这样的循环:

  while(objInput.available()>0){
Object obj = null;
obj = (String)objInput.readObject();
System.out.println(obj);}

或者类似的东西。

关于java - 服务器仅读取从客户端发送的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14341350/

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