gpt4 book ai didi

Java - 使用 ObjectInputStream 监听套接字

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:11:03 24 4
gpt4 key购买 nike

好的,我有一个名为“Client”的线程类,每次服务器接受连接时它都会创建一个新的客户端....run 方法监听来自客户端的消息,我正在使用 ObjectInputStream ..

   do {            
ObjectInputStream in = null;

try {
in = new ObjectInputStream(socket.getInputStream());
String message = (String) in.readObject();
System.out.println(message);
}
catch (ClassNotFoundException ex) {
isConnected = false;
System.out.println("Progoramming Error");
}
catch (IOException ex) {
isConnected = false;
System.out.println("Server ShutDown");
System.exit(0);
}
} while(isConnected);

我遇到的问题是,为什么每次循环时我都必须创建一个新的 ObjectInputStream ...如果我在循环结束时关闭输入流并再次循环以获取另一条消息,我将收到错误消息...请有人帮忙

最佳答案

只为客户端连接创建一次 ObjectInputStream(在循环外),然后将 readObject 方法放入循环中。

这是一个工作测试类:

public class TestPrg {

public static void main(String... args) throws IOException {
ServerListener server = new ServerListener();
server.start();

Socket socketToServer = new Socket("localhost", 15000);
ObjectOutputStream outStream = new ObjectOutputStream(socketToServer.getOutputStream());

for (int i=1; i<10; i++) {
try {
Thread.sleep((long) (Math.random()*3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Sending object to server ...");
outStream.writeObject("test message #"+i);
}
System.exit(0);

}

static class ServerListener extends Thread {

private ServerSocket serverSocket;

ServerListener() throws IOException {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(15000);
}

@Override
public void run() {
while (true) {
try {
final Socket socketToClient = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(socketToClient);
clientHandler.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

static class ClientHandler extends Thread{
private Socket socket;
ObjectInputStream inputStream;

ClientHandler(Socket socket) throws IOException {
this.socket = socket;
inputStream = new ObjectInputStream(socket.getInputStream());
}

@Override
public void run() {
while (true) {
try {
Object o = inputStream.readObject();
System.out.println("Read object: "+o);
} catch (IOException e) {
e.printStackTrace();

} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}

}

在此示例中,字符串通过 ObjectStream 发送。如果您获得 ClassNotFoundException (http://download.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html#readObject()) 并且使用的是独立的客户端和服务器程序,那么您可能会检查是否客户端和服务器都有要在其类路径中发送的对象类。

关于Java - 使用 ObjectInputStream 监听套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7022063/

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