我目前正在尝试让我的服务器创建与客户端的连接。我已经为每个连接创建了一个线程,但服务器当前没有创建输入流。我已经通过打印数字进行了测试,但只有1和2被打印出来。我确信这只是我遗漏的一个小问题。
public class ObjectHandler implements Runnable{
Socket sock;
ObjectInputStream ois;
ObjectOutputStream oops;
InputStream is;
public ObjectHandler(Socket clientSocket) throws IOException {
System.out.println("1");
sock = clientSocket;
is = sock.getInputStream();
System.out.println("2");
ois = new ObjectInputStream(new BufferedInputStream(is));
System.out.println("3");
OutputStream os = sock.getOutputStream();
oops = new ObjectOutputStream(new BufferedOutputStream(os));
outputSockets.add(oops);
}
我现在已经删除了throws IOException,并用try-catch包围了读取器。在客户端崩溃后,它现在打印此错误:
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ThreadPool$ObjectHandler.<init>(ThreadPool.java:95)
at ThreadPool.addThread(ThreadPool.java:31)
at ObjectServerTest.go(ObjectServerTest.java:93)
at ObjectServerTest.main(ObjectServerTest.java:124)
在套接字上构造Object流时,始终需要首先构造输出流,然后在创建输入流之前对其进行刷新(由于流的实现方式)。
删除BufferedInputStream
。您不需要它。它正在等待4K字节的读取。
编辑:也删除BufferedOutputStream
。并确保您正在刷新客户端的输出流。
这对我有用…
对象处理程序:
public ObjectHandler(Socket clientSocket) throws IOException {
System.out.println("1");
sock = clientSocket;
}
@Override
public void run() {
try {
is = sock.getInputStream();
System.out.println("2");
ois = new ObjectInputStream(new BufferedInputStream(is));
System.out.println("3"+ois.readFloat());
OutputStream os = sock.getOutputStream();
oops = new ObjectOutputStream(new BufferedOutputStream(os));
} catch (IOException e) {
e.printStackTrace();
}
}
客户:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client = new Socket(InetAddress.getByName("localhost"), 8888);
OutputStream os = client.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeFloat(new Float(10.10));
oos.flush();
}