1

I'm trying to send an arbitrary amount of objects through network in java. The problem is that it only sends one object and then throws an error when trying to send more then that, for a reason I don't know why.

Server main code:

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);
        }
    }

SendPackage class:

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();
    }
}

RecievePackage class:

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);
    }
}

Client main class:

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();
    }

Gives me the following error:

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)

I'm trying to send 1000 objects, but only succeed to send one. How to solve this?

user1319951
  • 495
  • 6
  • 16

0 Answers0