用 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方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html