--需求2:客户端发送信息给服务端,服务端接收信息,然后服务端发送信息回给客户端 --需求3:循环执行客户端和服务端交流【Scanner】、当输入exit退出
时间: 2023-11-04 10:05:47 浏览: 223
HP用SOCKET实现(客户端---服务端)
实现需求2和需求3的代码如下:
客户端:
```java
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
Socket client = new Socket("localhost", 8888);
Scanner scanner = new Scanner(System.in);
PrintStream out = new PrintStream(client.getOutputStream());
Scanner in = new Scanner(client.getInputStream());
boolean flag = true;
while (flag) {
System.out.print("请输入信息:");
String input = scanner.nextLine();
out.println(input);
if ("exit".equals(input)) {
flag = false;
continue;
}
if (in.hasNext()) {
String message = in.nextLine();
System.out.println("服务端回复:" + message);
}
}
scanner.close();
if (client != null) {
client.close();
}
}
}
```
服务端:
```java
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
System.out.println("等待客户端连接...");
Socket client = server.accept();
Scanner scanner = new Scanner(client.getInputStream());
PrintStream out = new PrintStream(client.getOutputStream());
boolean flag = true;
while (flag) {
if (scanner.hasNext()) {
String message = scanner.nextLine();
System.out.println("客户端发送:" + message);
if ("exit".equals(message)) {
flag = false;
continue;
}
out.println("服务端收到信息:" + message);
}
}
if (scanner != null) {
scanner.close();
}
if (client != null) {
client.close();
}
if (server != null) {
server.close();
}
}
}
```
运行上述代码后,可以在控制台输入信息进行通信,当输入exit时,就会退出程序。
阅读全文