一个最简单的socket的客户端和服务端,只是用来验证序列化传送数据。
第一次用序列化,记一下。
公用对象:
class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String saying;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSaying() {
return saying;
}
public void setSaying(String saying) {
this.saying = saying;
}
}
服务器端:
public class Service {
public static void main(String[] args) {
try {
ServerSocket serverSocket;
serverSocket = new ServerSocket(8088);
while (true) {
Socket socket = serverSocket.accept();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
User u = (User) in.readObject();
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
outStream.writeUTF("你好!你是?"+u.getName()+"你想说:"+u.getSaying());
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
public class client {
Socket socket = null;
DataInputStream inStream = null;
DataOutputStream outStream = null;
private void waitData() {
System.out.println("waitData");
String acceptStr;
try {
acceptStr = inStream.readUTF();
System.out.println( acceptStr);
} catch (IOException e) {
e.printStackTrace();
}
}
private void send(User l) {
System.out.println("send");
try {
ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
os.writeObject(l);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void init() throws UnknownHostException, IOException {
System.out.println("init");
socket = new Socket("127.0.0.1", 8088);
inStream = new DataInputStream(socket.getInputStream());
outStream = new DataOutputStream(socket.getOutputStream());
}
public static void main(String[] args) {
client client = new client();
try {
while (true) {
System.out.print("姓名:内容");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s = in.readLine();
String[] lis = s.split(":");
User u = new User();
u.setName(lis[0]);
u.setSaying(lis[1]);
client.init();
client.send(u);
client.waitData();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端输入 wty:faaaa 输出 你好!你是?wty你想说faaaa
关于transient 就是对象中不想序列化的内容
这篇文章不错:http://onlylove.javaeye.com/blog/161034
第一个序列化程序 socket例子
最新推荐文章于 2022-12-06 15:39:27 发布