我正在创建一个 java 服务器和一个 java 客户端。我需要从服务器向客户端发送一个对象,然后是一个对象数组,反之亦然。我怎样才能做到这一点?我需要序列化对象类吗?
这是服务器:
import java.io.*;
import java.net.*;
public class Server extends Thread {
private final ServerSocket Server;
public static void main(String[] args) throws Exception {
new Server();
}
public Server() throws Exception {
Server = new ServerSocket(3000);
System.out.println("Server started on port 3000.");
this.start();
}
@Override
public void run() {
while (true) {
try {
System.out.println("Server is listening to new connections...");
Socket client = Server.accept();
System.out.println("Connection accepted from: " + client.getInetAddress());
Connect c = new Connect(client);
} catch (IOException exception) {
System.out.println(exception.getMessage());
}
}
}
class Connect extends Thread {
private Socket client = null;
BufferedReader in = null;
PrintStream out = null;
public Connect(Socket clientSocket) {
client = clientSocket;
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream(client.getOutputStream(), true);
} catch (IOException mainException) {
try {
client.close();
} catch (IOException exception) {
System.out.println(exception.getMessage());
}
}
this.start();
}
@Override
public void run() {
try {
out.close();
in.close();
client.close();
} catch (IOException exception) {
System.out.println(exception.getMessage());
}
}
}
这是我的客户:
import java.io.*;
import java.net.*;
public class Client {
String remoteAddress = "localhost";
BufferedReader in = null;
PrintStream out = null;
Socket socket = null;
String message = null;
String username = null;
String password = null;
public Client(String username, String password) {
this.username = username;
this.password = password;
}
public String connect() {
try {
// begin a new client connection
socket = new Socket(remoteAddress, 3000);
// open I-O channels
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream(), true);
} catch (Exception exception) {
return false;
System.out.println(exception.getMessage());
}
return "ERROR";
}
public boolean disconnect() throws IOException {
// close flushes I-O with the server
out.close();
in.close();
return true;
}
}
相反,这是一类:
class Contact {
private String name;
private String surname;
private String telephone;
private String birthday;
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getTelephone() {
return telephone;
}
public String getBirthday() {
return birthday;
}
public void setName(String value) {
name = value;
}
public void setSurname(String value) {
surname = value;
}
public void setTelephone(String value) {
telephone = value;
}
public void setBirthday(String value) {
birthday = value;
}
}
目前只有服务器可以向客户端发送数据(对象数组或唯一对象),但我正在考虑让两者都能做到。此外,最好发送一个对象(如上面的类)、一个相同对象的数组和一个不同对象的数组(我无法使用经典数组获得它,对吗?我可以使用ArrayList
吗?)
谢谢你。