在Java中使用Socket发送Java对象实例需要完成以下几个步骤:
-
序列化Java对象实例:将Java对象实例转换成字节流,以便在网络传输中能够被传输。
-
创建Socket连接:需要在发送方和接收方创建Socket连接,可以使用Socket类和ServerSocket类完成。
-
发送字节流:通过Socket连接,将序列化的Java对象实例以字节流形式发送给接收方。
-
反序列化Java对象实例:接收方接收到字节流后,需要将字节流反序列化成Java对象实例。
下面是Java中使用Socket发送Java对象实例的示例:
示例1:发送方
public class Sender {
public static void main(String[] args) {
try {
// 写入对象
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("data.obj"));
User user = new User("Tom", 18, "Beijing");
objectOutputStream.writeObject(user);
objectOutputStream.close();
// 发送对象
Socket socket = new Socket("localhost", 8888);
FileInputStream fileInputStream = new FileInputStream("data.obj");
OutputStream outputStream = socket.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
socket.shutdownOutput();
fileInputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
示例2:接收方
public class Receiver {
public static void main(String[] args) {
try {
//读取对象
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("data.obj"));
User user = (User) objectInputStream.readObject();
objectInputStream.close();
System.out.println(user.toString());
//接收对象
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("object.obj");
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) != -1) {
fileOutputStream.write(buf, 0, len);
}
inputStream.close();
fileOutputStream.close();
socket.close();
serverSocket.close();
//反序列化对象
ObjectInputStream objectInputStream1 = new ObjectInputStream(new FileInputStream("object.obj"));
User user1 = (User) objectInputStream1.readObject();
objectInputStream1.close();
System.out.println(user1.toString());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在示例中,我们通过一个User对象演示了如何在Java中使用Socket发送Java对象实例。首先,发送方需要将User对象序列化成字节流,然后通过Socket连接将字节流发送给接收方。接收方接收到字节流后,需要将字节流反序列化成User对象。通过上述示例,我们可以在Java中实现Socket通信并发送Java对象实例。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java中使用Socket发送Java对象实例 - Python技术站