对象类代码
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Accessors(chain = true)
public class Userinfo implements Serializable {
private long id;
private String username;
private String password;
public Userinfo() {
}
public Userinfo(long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
}
服务端代码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ServerSocket serverSocket = new ServerSocket(5678);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
for (int i = 0; i < 5; i++) {
Userinfo userinfo = (Userinfo) objectInputStream.readObject();
System.out.println("在服务端打印" + (i + 1) + ":" + userinfo.getId() + " " + userinfo.getUsername() + " " + userinfo.getPassword());
Userinfo userinfo1 = new Userinfo();
userinfo1.setId(i + 1).setUsername("serverUsername" + (i + 1)).setPassword("serverPassword" + (i + 1));
objectOutputStream.writeObject(userinfo1);
}
objectOutputStream.close();
objectInputStream.close();
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
客户端代码
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Socket socket = new Socket("localhost", 5678);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
for (int i = 0; i < 5; i++) {
Userinfo userinfo1 = new Userinfo();
userinfo1.setId(i + 1).setUsername("clientUsername" + (i + 1)).setPassword("clientPassword" + (i + 1));
objectOutputStream.writeObject(userinfo1);
Userinfo userinfo = (Userinfo) objectInputStream.readObject();
System.out.println("在客户端打印" + (i + 1) + ":" + userinfo.getId() + " " + userinfo.getUsername() + " " + userinfo.getPassword());
}
objectOutputStream.close();
objectInputStream.close();
outputStream.close();
inputStream.close();
socket.close();
}
}
|