当前位置: 首页 > 知识库问答 >
问题:

Java网络:解释套接字中的InputStream和OutputStream

杭志泽
2023-03-14

我使用ServerSocket创建了一个服务器。之后,我使用socket创建了客户机,并连接到该服务器。

之后,我对InputStream做了“一些事情”,而OutputStream是从套接字对象中获取的。但是,我不太理解inputStream和outputStream。下面是我的简单代码:

private Socket sock = null;
private InputStream sockInput = null;
private OutputStream sockOutput = null;

...
            String msg = "Hello World";
            byte[] buffer = null;

            try {
                sockOutput.write(msg.getBytes(), 0, test.length());
                sockOutput.write("Hello StackOverFlow".getBytes(), 0, test.length());
                buffer = new byte[test.length()];
                sockInput.read(buffer, 0, test.length());
                System.out.println(new String(buffer));
                sockInput.read(buffer, 0, test.length());
                System.out.println(new String(buffer));
            } catch (IOException e1) {
                e1.printStackTrace();
                }

结果将是:“Hello World”和“Hello StackOverflow”。

以下是服务器端代码:

private int serverPort = 0;
    private ServerSocket serverSock = null;

    public VerySimpleServer(int serverPort) {
        this.serverPort = serverPort;

        try {
            serverSock = new ServerSocket(this.serverPort);
        }
        catch (IOException e){
            e.printStackTrace(System.err);
        }
    }

    // All this method does is wait for some bytes from the
    // connection, read them, then write them back again, until the
    // socket is closed from the other side.
    public void handleConnection(InputStream sockInput, OutputStream sockOutput) {
        while(true) {
            byte[] buf=new byte[1024];
            int bytes_read = 0;
            try {
                // This call to read() will wait forever, until the
                // program on the other side either sends some data,
                // or closes the socket.
                bytes_read = sockInput.read(buf, 0, buf.length);

                // If the socket is closed, sockInput.read() will return -1.
                if(bytes_read < 0) {
                    System.err.println("Server: Tried to read from socket, read() returned < 0,  Closing socket.");
                    return;
                }
                System.err.println("Server: Received "+bytes_read
                                   +" bytes, sending them back to client, data="
                                   +(new String(buf, 0, bytes_read)));
                sockOutput.write(buf, 0, bytes_read);
                // This call to flush() is optional - we're saying go
                // ahead and send the data now instead of buffering
                // it.
                sockOutput.flush();
            }
            catch (Exception e){
                System.err.println("Exception reading from/writing to socket, e="+e);
                e.printStackTrace(System.err);
                return;
            }
        }

    }

    public void waitForConnections() {
        Socket sock = null;
        InputStream sockInput = null;
        OutputStream sockOutput = null;
        while (true) {
            try {
                // This method call, accept(), blocks and waits
                // (forever if necessary) until some other program
                // opens a socket connection to our server.  When some
                // other program opens a connection to our server,
                // accept() creates a new socket to represent that
                // connection and returns.
                sock = serverSock.accept();
                System.err.println("Server : Have accepted new socket.");

                // From this point on, no new socket connections can
                // be made to our server until we call accept() again.

                sockInput = sock.getInputStream();
                sockOutput = sock.getOutputStream();
            }
            catch (IOException e){
                e.printStackTrace(System.err);
            }

            // Do something with the socket - read bytes from the
            // socket and write them back to the socket until the
            // other side closes the connection.
            handleConnection(sockInput, sockOutput);

            // Now we close the socket.
            try {
                System.err.println("Closing socket.");
                sock.close();
            }
            catch (Exception e){
                System.err.println("Exception while closing socket.");
                e.printStackTrace(System.err);
            }

            System.err.println("Finished with socket, waiting for next connection.");
        }
    }

    public static void main(String argv[]) {
        int port = 54321;
        VerySimpleServer server = new VerySimpleServer(port);
        server.waitForConnections();
    }

我的问题是:

>

  • 当我使用sockoutput.write时,我可以通过sockinput.read返回这些消息。那么,那些信息已经被保存了,对吧?如果为真,它是保存在我创建的服务器上,还是保存在其他东西中,如socket对象

    如果我已经写入套接字字符串A1,A2,······所以我会分别收到A1,A2,…一个字符串,对吗?

  • 共有1个答案

    桑宇
    2023-03-14

    套接字是一种抽象,用于通过网络与某些东西进行对话。请参见下图...

    在Java中,要通过套接字发送数据,需要从它获得outputstream(1),并写入outputstream(输出一些数据)。

    要从套接字读取数据,需要获取它的inputstream,并从第二个流读取输入。

    你可以把溪流看作是一对连接到墙上插座上的单向管道。在墙的另一边发生的事不是你的问题!

    在您的例子中,服务器有另一个套接字(连接的另一端)和另一对流。它使用其inputstream(2)从网络读取数据,并使用其outputstream(3)通过网络将相同的数据写回客户端,客户端通过其inputstream(4)再次读取数据。

          Client                                                     Server
    
    1. OutputStream -->\                                     /--> 2. InputStream -->
                        Socket <--> network <--> ServerSocket                       |
    4. InputStream  <--/                                     \<--3. OutputStream <--
    

    更新:在回复评论时:

     类似资料:
    • 问题内容: 我已经使用创建了服务器。之后,我使用创建了Client ,并连接到该服务器。 之后,我对InputStream和OutputStream进行了“一些处理”,它们是从Socket Object中获取的。但是,我不太了解inputStream和outputStream。这是我的简单代码: 结果将是:“ Hello World”和“ Hello StackOverFlow”。 这是服务器端代

    • 我已经开发了Android应用程序,并且连接到JAVA Web Socket,基本上它运行得很好。问题是,有时客户端断开连接,但服务器端的连接似乎已连接。 我试图调查它发生的时间和原因,但不幸的是,我找不到导致这个问题的具体情况。 我想在服务器和所有客户端之间实现乒乓消息,如果客户端没有响应,就关闭服务器端的连接。 我可以很容易地实现这样的我的私人机制,但我已经阅读了周围,我知道Java和Andr

    • 计算机网络基础 ip地址 为了使网络上的计算机能够彼此识别对方,每台计算机都需要一个IP地址以标识自己。 IPv4:32位,IPv6:64位 OSI七层参考模型 应用层 表示层 会话层 传输层 网络层 数据链路层 物理层 地址解析 地址解析是指将计算机的协议地址解析为物理地址,即MAC(Medium Access Control)地址,又称为媒体访问控制地址。通常,在网络上由地址解析协议(ARP)

    • 本文向大家介绍Java套接字(Socket)网络编程入门,包括了Java套接字(Socket)网络编程入门的使用技巧和注意事项,需要的朋友参考一下 网络应用模式主要有: 主机/终端模式:集中计算,集中管理; 客户机/服务器(Client/Server,简称C/S)模式:分布计算,分布管理; 浏览器/服务器模式:利用Internet跨平台。 www(万维网)就是建立在客户机/服务器模式上,以HTML

    • 问题内容: 我正在Java套接字上实现面向事件的层,我想知道是否有一种方法可以确定是否有待读取的数据。 我通常的方法是从套接字读取一个缓冲区,并在给定字节数的缓冲区中填充缓冲区时调用提供的回调(如果每次到达时都需要触发该回调,则可以为0),但是我怀疑Java已经在为我做缓冲了。 InputStream 的方法对此是否可靠?我应该只是在套接字顶部做自己的缓冲吗?还是有另一种方法? 问题答案: 简短地

    • 关于BufferedInputStream的使用,我有几个问题: 首先,我听说BufferedInputStream可以显著提高性能,如果您从硬盘上逐字节读取数据的话。 > 在这里使用BufferedInputStream会被证明非常有用吗? 同样,BufferedInputStream在逐字节读取时是否仅在套接字中起作用,即逐字节读取是否仅对预加载缓冲区有用?