【网络原理】使用Java基于TCP搭建简单客户端与服务器通信
以下是一个简单的Java TCP Socket客户端和服务器端的例子。服务器端接收客户端发送的消息并将其打印出来。
服务器端 (Server.java):
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(1234); // 监听1234端口
Socket socket = serverSocket.accept(); // 等待客户端连接
System.out.println("Client connected!");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
System.out.println("Client says: " + str);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Server received the message.");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
serverSocket.close();
}
}
}
}
客户端 (Client.java):
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
try {
socket = new Socket("localhost", 1234); // 连接到本地主机的1234端口
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello from Client"); // 发送消息
System.out.println("Client says: Hello from Client");
String response = in.readLine(); // 接收响应
System.out.println("Server says: " + response);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
}
在运行这些代码之前,请确保没有其他服务占用1234端口。运行服务器端 (Server.java) 将会创建一个监听1234端口的服务器,然后运行客户端 (Client.java) 将会连接到服务器并发送消息。服务器接收到消息后,将响应客户端并关闭连接。
评论已关闭