用 Java 套接字发送和接收字符串32


Java 套接字 API 提供了一种机制,允许应用程序通过网络连接进行通信。使用套接字,您可以从一个进程(客户端)向另一个进程(服务器)发送和接收数据。在本文中,我们将重点介绍如何使用 Java 套接字发送和接收字符串。

让我们创建一个服务器,它将侦听传入的连接并接收和发送字符串。服务器端代码如下:```java
import ;
import ;
import ;
import ;
import ;
public class Server {
public static void main(String[] args) {
// 创建一个服务器套接字,侦听端口 9090
try (ServerSocket serverSocket = new ServerSocket(9090)) {
while (true) {
// 接受传入连接并创建套接字对象
Socket socket = ();
// 获取输入流以读取从客户端发送的字符串
BufferedReader in = new BufferedReader(new InputStreamReader(()));
// 读取并打印从客户端接收的字符串
String message = ();
("Received message: " + message);
// 发送字符串回复客户端
String reply = "Hello from the server!";
PrintWriter out = new PrintWriter((), true);
(reply);
}
} catch (IOException e) {
();
}
}
}
```

接下来,让我们创建一个客户端,它将连接到服务器并发送和接收字符串。客户端端代码如下:```java
import ;
import ;
import ;
import ;
import ;
public class Client {
public static void main(String[] args) {
// 创建一个客户端套接字,连接到服务器端的端口 9090
try (Socket socket = new Socket("localhost", 9090)) {
// 获取输入流以读取从服务器发送的字符串
BufferedReader in = new BufferedReader(new InputStreamReader(()));
// 获取输出流以向服务器发送字符串
PrintWriter out = new PrintWriter((), true);
// 从用户输入读取要发送的字符串
BufferedReader console = new BufferedReader(new InputStreamReader());
("Enter a message to send to the server:");
String message = ();
// 向服务器发送字符串
(message);
// 接收并打印从服务器收到的字符串
String reply = ();
("Received reply from the server: " + reply);
} catch (IOException e) {
();
}
}
}
```

要运行程序,请先编译服务器和客户端类,然后在不同的终端窗口中启动服务器和客户端程序。

在服务器程序窗口中,您将看到以下输出:```
Waiting for client connections on port 9090...
Received message: Hello from the client!
```

在客户端程序窗口中,您将看到以下输出:```
Enter a message to send to the server:
Hello from the client!
Received reply from the server: Hello from the server!
```

通过本文,您已经了解了如何使用 Java 套接字在客户端和服务器应用程序之间发送和接收字符串。我们提供了服务器和客户端端的示例代码,并且演示了如何在本地运行这些程序。这些概念对于构建需要通过网络进行字符串通信的应用程序至关重要。

2024-11-21


上一篇:Java 中保存数组到文件

下一篇:Java 二维码生成指南:轻松创建和定制二维码