1、TCP Socket编程实现服务器和客户端的交互: (1)服务器端先运行,利用循环时刻为客户端提供服务; (2)客户端与服务器接通后,从键盘上输入若干字符(若客户端发送“end”字符串,服务器终止程序),传到服务器,服务器在控制台显示所收到的数据,形式为:”I have received ******”,并向客户端 反馈信息“Message from Server is:******”,此次通话结束; (3)客户端接收来自服务器端的数据,在控制台显示:“Client has received .............“。
时间: 2023-07-24 15:33:59 浏览: 172
下面是TCP Socket实现服务器和客户端交互的代码:
服务器端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("Server is listening on port 8888...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from client " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message from client: " + inputLine);
if ("end".equals(inputLine)) {
break;
}
out.println("Message from Server is: " + inputLine);
System.out.println("Sent message to client: " + inputLine);
}
in.close();
out.close();
clientSocket.close();
System.out.println("Connection with client closed.");
}
}
}
```
客户端代码:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
String hostName = "localhost";
int portNumber = 8888;
try (Socket socket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if ("end".equals(userInput)) {
break;
}
System.out.println("Client has sent message: " + userInput);
String serverResponse = in.readLine();
System.out.println("Server response: " + serverResponse);
}
} catch (IOException e) {
System.err.println("Could not connect to " + hostName + ":" + portNumber);
System.exit(1);
}
}
}
```
在客户端中,用户输入的信息通过PrintWriter的println方法发送给服务器端;服务器端收到信息后,在控制台显示,并通过PrintWriter的println方法向客户端反馈信息;客户端收到服务器端的信息后,在控制台显示。当用户输入"end"时,程序结束。
阅读全文