为什么找不到getInputStream?
我有这样的代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
accept
返回Socket
实例,该实例具有所需的方法getInputStream
。代码可能如下所示:
很棒的教程如何在 java 中使用套接字: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
Calling of
accept
returns instance ofSocket
which has required methodgetInputStream
.The code might look like this:
Great tutorial how to work with sockets in java: http://java.sun.com/docs/books/tutorial/networking/sockets/index.html
这是因为从概念上讲,
ServerSocket
不提供可用于发送和接收数据的直接连接对象。ServerSocket
是一种工具,您可以将其与.accept()
方法结合使用,让它侦听所选端口,并在客户端尝试连接时生成新的真实连接。这就是为什么您无法从
ServerSocket
获取InputStream
的原因。由于许多客户端可以连接到同一服务器,因此每个客户端都会使服务器套接字生成一个从返回的新
通过它,您可以使用其Socket
(即打开的 TCP 连接) .accept()InputStream
和OutputStream
进行发送和接收。This because conceptually a
ServerSocket
doesn't provide a direct connection object that can be used to send and receive data. AServerSocket
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 aServerSocket
. Since many clients can connect to the same server, every client will make the server socket generate a newSocket
(that is an opened TCP connection) that is returned from.accept()
through which you can send and receive using itsInputStream
andOutputStream
.