我是 Java 初学者,所以我需要什么来完成这项工作?我制作类,在其中添加了粘贴此代码的主要方法,但这不起作用。在服务器类中给了我一些关于 finally 变量的错误。我什么都不懂。
客户端类
//Creating the client socket:
Socket socket = new Socket ();
//Binding to the local socket address:
InetAddress localIpAddress = InetAddress.getByName ("0.0.0.0");
int localIpPort = 0;
SocketAddress localSocketAddress = new InetSocketAddress (localIpAddress, localIpPort);
socket.bind (localSocketAddress);
//Connecting to the remote socket address:
InetAddress remoteIpAddress = InetAddress.getByName ("localhost");
int remoteIpPort = 20000;
SocketAddress remoteSocketAddress = new InetSocketAddress (remoteIpAddress, remoteIpPort);
socket.connect (remoteSocketAddress);
//Receiving and/or sending data through inbound and outbound streams:
BufferedReader reader = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (socket.getOutputStream ()));
String request = "Hello";
writer.write (request);
writer.newLine ();
// Do not forget to flush
writer.flush ();
// Reading the response
String response = reader.readLine ();
//Shutting-down the inbound and outbound streams:
socket.shutdownInput ();
socket.shutdownOutput ();
//Closing the socket:
socket.close ();
[...]
服务器类
//Creating the server socket:
ServerSocket socket = new ServerSocket ();
//Binding to the local socket address -- this is the one the clients should be connecting to:
InetAddress localIpAddress = InetAddress.getByName ("0.0.0.0");
int localIpPort = 20000;
SocketAddress localSocketAddress = new InetSocketAddress (localIpAddress, localIpPort);
socket.bind (localSocketAddress);
while (true) {
//For each connection accepting a client socket, and:
Socket client = socket.accept ();
// Starting a new Thread for each client
new Thread () {
public void run () {
try {
//Receiving and/or sending data;
BufferedReader reader = new BufferedReader (new InputStreamReader (client.getInputStream ()));
BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (client.getOutputStream ()));
// Reading the request
String request = reader.readLine ();
// Write the response
String response = "Welcome";
writer.write(response);
writer.newLine();
// Do not forget to flush!
writer.flush();
client.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
//Closing the server socket;
socket.close ();