package com.wet.TCP;
import java.io.*;
/**
* 所要传输的对象
*
* @author Administrator
*
*/
public class Message implements Serializable {
private String message;
private String time;
public Message() {
}
public Message(String messtime, String time) {
this.message = messtime;
this.time = time;
}
public String getMesstime() {
return message;
}
public void setMesstime(String messtime) {
this.message = messtime;
}
public String gettime() {
return time;
}
public void settime(String time) {
this.time = time;
}
@Override
public String toString() {
return "[message=" + message + ", time=" + time + "]";
}
}
package com.wet.TCP;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* TCP服务器之对象流传输
*/
public class TCPObjectServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8888); // 建绑定到特定端口的服务器套接字
Socket s = ss.accept(); // 侦听并接受到此套接字的连接
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
Message mess = (Message) in.readObject();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("来自客户端的对象信息:" + mess + sdf.format(new Date()));
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
Message message = new Message("你好服务器", new Date().toLocaleString());
out.writeObject(message);
out.close();
in.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
package com.wet.TCP;
import java.io.*;
import java.net.*;
import java.util.Date;
/**
* TCP客户端之对象传输流
*
* @author Administrator
*
*/
public class TCPObjectClient {
public static void main(String[] args) {
try {
// 创建一个流套接字并将其连接到指定 IP 地址的指定端口号
Socket s = new Socket("127.0.0.1", 8888);
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
Message mess = new Message("你好服务器", new Date().toLocaleString());
out.writeObject(mess);
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
Message message = (Message) in.readObject();
System.out.println("来自客户端的消息:" + message);
in.close();
out.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}