//需求2:客户端发送信息给服务端,服务端接收信息,然后服务端发送信息回给客户端 //需求3:循环执行客户端和服务端交流【Scanner】
时间: 2023-07-05 20:34:07 浏览: 203
这是一个简单的客户端-服务端通信的代码示例,需要使用 Java 的 Socket 编程实现:
服务端代码:
```
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server started.");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine);
out.println("Server: " + inputLine);
}
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
System.out.println("Connected to server.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
String inputLine;
while (true) {
System.out.print("Client: ");
inputLine = scanner.nextLine();
out.println(inputLine);
System.out.println("Server: " + in.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这里使用了 Scanner 来循环执行客户端和服务端的交流。
阅读全文