1

我正在尝试通过java中的网络发送任意数量的对象。问题是它只发送一个对象,然后在尝试发送更多对象时抛出错误,原因我不知道为什么。

服务器主要代码:

public static void main(String[] args) throws IOException, ClassNotFoundException{
        System.out.println("Waiting for players to connect");
        int port = 4444;
        ServerSocket serverSocket = new ServerSocket(port);
        Socket clientSocket = serverSocket.accept();
        System.out.println("Player connected");
        Package testPackage;
        SendPackage sendPackage;
        for(int i=0;i<1000;i++){
            testPackage = new Package(new Order(i,i),null,false);
            sendPackage = new SendPackage(testPackage,clientSocket);
        }
    }

发送包类:

import java.io.*;
import java.net.*;

public class SendPackage{

    public SendPackage(Package pck, Socket receiver) throws IOException {
        ObjectOutputStream send = new ObjectOutputStream(receiver.getOutputStream());
        send.writeObject(pck);
        send.flush();
        send.close();
    }
}

接收包类:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;


public class ReceivePackage extends Thread {
    Socket sender;
    ObjectInputStream receive;

    public ReceivePackage(Socket sender) throws ClassNotFoundException, IOException{
        this.sender=sender;
    }

    public void run(){
        try {
            while(true)
                listen();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void listen() throws IOException, ClassNotFoundException {
        receive = new ObjectInputStream(sender.getInputStream());
        Package pck = (Package) receive.readObject();
        System.out.println(pck.order.quantity);
    }
}

客户端主类:

public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException{
        Socket clientSocket = new Socket("192.168.0.7", 4444);
        System.out.println("Connected");
        receivePackage = new ReceivePackage(clientSocket);
        receivePackage.start();
    }

给我以下错误:

Connected
0
java.io.EOFException
    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 ReceivePackage.listen(ReceivePackage.java:42)
    at ReceivePackage.run(ReceivePackage.java:31)

我正在尝试发送 1000 个对象,但只能成功发送一个。如何解决这个问题?

4

0 回答 0