8

我正在尝试通过 TCP 将一个对象从服务器端套接字发送到客户端套接字。我找不到问题出在哪里。

这是我在客户端遇到的错误:

java.io.EOFException
    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 ClientSide.main(ClientSide.java:16)

服务器端代码:

import java.io.*;
import java.net.*;
import java.util.ArrayList;

public class ServerSide {

    public static void main(String[] args) {
        try
        {
            ServerSocket myServerSocket = new ServerSocket(9999);
            Socket skt = myServerSocket.accept();   
            ArrayList<String> my =  new ArrayList<String>();
            my.set(0,"Bernard");
            my.set(1, "Grey");
            try 
            {
                ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream());
                objectOutput.writeObject(my);               
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            } 
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }

}

客户端代码:

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;


public class ClientSide {

    public static void main(String[] args)
    {
        try {       
            Socket socket = new Socket("10.1.1.2",9999);
            ArrayList<String> titleList = new ArrayList<String>();
            try {
                ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); //Error Line!
                try {
                    Object object = objectInput.readObject();
                    titleList =  (ArrayList<String>) object;
                    System.out.println(titleList.get(1));
                } catch (ClassNotFoundException e) {
                    System.out.println("The title list has not come from the server");
                    e.printStackTrace();
                }
            } catch (IOException e) {
                System.out.println("The socket for reading the object has problem");
                e.printStackTrace();
            }           
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }   
}
4

1 回答 1

8

set到改变add诀窍

ArrayList<String> my =  new ArrayList<String>();
my.add("Bernard");
my.add("Grey");

附言。正如其他人所建议的那样,这不是一个好主意,但仅用于学习

于 2012-10-15T12:22:54.367 回答