发送ArrayList< String>从服务器端到客户端通过TCP使用套接字? [英] Sending an ArrayList<String> from the server side to the client side over TCP using socket?
本文介绍了发送ArrayList< String>从服务器端到客户端通过TCP使用套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过TCP将一个对象从服务器端套接字发送到客户端套接字。我无法找出问题所在。
I'm trying to send one object from the server side socket to the client side socket over TCP. I can't find out where is the problem.
以下是我在客户端遇到的错误:
Here is the error I'm getting on the Client side:
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();
}
}
}
推荐答案
从设置
更改添加
可以解决这个问题
Changing from set
to add
does the trick
ArrayList<String> my = new ArrayList<String>();
my.add("Bernard");
my.add("Grey");
ps。根据其他人的建议,这不是一个好主意,但仅用于学习
ps. as advised by the others this is not a good idea but, use only for learning
这篇关于发送ArrayList< String>从服务器端到客户端通过TCP使用套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文