1. 实现Serializable的Object
package com.qdl.test;
import java.io.Serializable;
public class TestObject implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2. 建立一个server用来接收object
package com.qdl.test;
import java.net.ServerSocket;
import java.net.Socket;
public class SendServer extends java.lang.Thread {
private boolean OutServer = false;
private ServerSocket server;
private final int ServerPort = 8765;
public SendServer() {
try {
server = new ServerSocket(ServerPort);
System.out.println("The server is running...");
} catch (java.io.IOException e) {
System.out.println("Socket start-up error!");
System.out.println("IOException :" + e.toString());
}
}
public void run() {
Socket socket;
java.io.ObjectInputStream in;
while (!OutServer) {
socket = null;
try {
synchronized (server) {
socket = server.accept();
}
System.out.println("Built a connection: InetAddress = "
+ socket.getInetAddress());
socket.setSoTimeout(15000);
in = new java.io.ObjectInputStream(socket.getInputStream());
TestObject data = (TestObject) in.readObject();
System.out.println("The value received:" + data.getName());
in.close();
in = null;
socket.close();
} catch (java.io.IOException e) {
System.out.println("Socket connection error!");
System.out.println("IOException :" + e.toString());
} catch (java.lang.ClassNotFoundException e) {
System.out.println("ClassNotFoundException :" + e.toString());
}
}
}
public static void main(String args[]) {
(new SendServer()).start();
}
}
3. 创建一个client测试一下
package com.qdl.test;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class SendClient {
private String address = "127.0.0.1";
private int port = 8765;
public SendClient() {
// Prepare the data need to transmit
TestObject data = new TestObject();
data.setName("Scott");
Socket client = new Socket();
InetSocketAddress isa = new InetSocketAddress(this.address, this.port);
try {
client.connect(isa, 10000);
ObjectOutputStream out = new ObjectOutputStream(
client.getOutputStream());
// send object
out.writeObject(data);
out.flush();
out.close();
out = null;
data = null;
client.close();
client = null;
} catch (java.io.IOException e) {
System.out.println("Socket connection error!");
System.out.println("IOException :" + e.toString());
}
}
public static void main(String args[]) {
new SendClient();
}
}
阅读(4563) | 评论(1) | 转发(0) |