我有一个Socket,我想从客户端发送到服务器(或反向)。
当java.net.Socket
落在java.lang.Object
下时,为什么不能使用ObjectStream ?我怎样才能做得正确呢?
Server.java :
package com.company;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket ss = new ServerSocket(1234); // make server on localhost:1234
Socket socket = ss.accept();
System.out.println("Connection from " + socket + "!n");
InputStream inputStream = socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Socket receivedSocket = (Socket) objectInputStream.readObject();
System.out.println(receivedSocket);
ss.close();
socket.close();
}
}
这是Client.java:
package com.company;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234); // make socket on localhost:1234
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(socket); // send `socket` over network
socket.close();
}
}
在Client
端,它抛出了这个异常:
Exception in thread "main" java.io.NotSerializableException: java.net.Socket
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1192)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:352)
at com.company.Client.main(Client.java:14)
Server
这边:
Exception in thread "main" java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.net.Socket
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1696)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:495)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:453)
at com.company.Server.main(Server.java:17)
Caused by: java.io.NotSerializableException: java.net.Socket
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1192)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:352)
at com.company.Client.main(Client.java:14)
提前感谢!
您只能编写实现java.io.Serializable
接口的对象。您可以创建一个配置类,其中包含来自套接字的信息:
public class SocketConfiguration implements Serializable {
private final String host;
private final int port;
public SocketConfiguration(String host, int port) {
this.host = host;
this.port = port;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
}
虽然上面的例子是毫无意义的,因为所有这些信息都是你已经知道的。你也可以创建一个类来扩展java.net.Socket
并实现java.io.Serializable
,但我真的不认为这样做有什么意义。