java – 使用套接字通过TCP从服务器端向客户端发送ArrayList?

前端之家收集整理的这篇文章主要介绍了java – 使用套接字通过TCP从服务器端向客户端发送ArrayList?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试通过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();
        }   
    }   
}

解决方法

从set更改为add可以解决问题
ArrayList<String> my =  new ArrayList<String>();
my.add("Bernard");
my.add("Grey");

PS.根据其他人的建议,这不是一个好主意,但仅用于学习

原文链接:https://www.f2er.com/java/128959.html

猜你在找的Java相关文章