为什么找不到getInputStream?

发布于 2024-08-26 11:03:53 字数 317 浏览 5 评论 0原文

我有这样的代码:

ServerSocket serverSideSocket = new ServerSocket(1234);
        serverSideSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));

编译器告诉我它找不到“getInputStream”。我不明白为什么。在代码的开头,我导入 java.net.*

I have this code:

ServerSocket serverSideSocket = new ServerSocket(1234);
        serverSideSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(serverSideSocket.getInputStream()));

And compiler writes me that it cannot find "getInputStream". I do not understand why. In the beginning of my code I do import java.net.*.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

灵芸 2024-09-02 11:03:54

调用 accept 返回 Socket 实例,该实例具有所需的方法 getInputStream

代码可能如下所示:

ServerSocket serverSideSocket = new ServerSocket(1234);
Socket socket = serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

很棒的教程如何在 java 中使用套接字: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

Calling of accept returns instance of Socket which has required method getInputStream.

The code might look like this:

ServerSocket serverSideSocket = new ServerSocket(1234);
Socket socket = serverSideSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Great tutorial how to work with sockets in java: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

何时共饮酒 2024-09-02 11:03:54

这是因为从概念上讲,ServerSocket 不提供可用于发送和接收数据的直接连接对象。 ServerSocket 是一种工具,您可以将其与 .accept() 方法结合使用,让它侦听所选端口,并在客户端尝试连接时生成新的真实连接。

这就是为什么您无法从 ServerSocket 获取 InputStream 的原因。由于许多客户端可以连接到同一服务器,因此每个客户端都会使服务器套接字生成一个从 返回的新 Socket (即打开的 TCP 连接) .accept() 通过它,您可以使用其 InputStreamOutputStream 进行发送和接收。

This because conceptually a ServerSocket doesn't provide a direct connection object that can be used to send and receive data. A ServerSocket is a tool that you can use with the .accept() method to let it listen on the choosen port and generate a new real connection when a client tries to connect.

That's why you can't get an InputStream from a ServerSocket. Since many clients can connect to the same server, every client will make the server socket generate a new Socket (that is an opened TCP connection) that is returned from .accept() through which you can send and receive using its InputStream and OutputStream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文