如何读取服务器套接字 JAVA 中的所有 Inputstream

How to read all of Inputstream in Server Socket JAVA(如何读取服务器套接字 JAVA 中的所有 Inputstream)

本文介绍了如何读取服务器套接字 JAVA 中的所有 Inputstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个项目中使用 Java.net.我编写了一个从客户端获取 inputStream 的 App Server.但有时我的(缓冲的)InputStream 无法获取客户端发送到我的服务器的所有 OutputStream.我怎样才能写一个等待或类似的东西,让我的 InputStream 获得客户端的所有 OutputStream?

I am using Java.net at one of my project. and I wrote a App Server that gets inputStream from a client. But some times my (buffered)InputStream can not get all of OutputStream that client sent to my server. How can I write a wait or some thing like that, that my InputStream gets all of the OutputStream of client?

(我的 InputStream 不是字符串)

(My InputStream is not a String)

private Socket clientSocket;
private ServerSocket server;
private BufferedOutputStream outputS;
private BufferedInputStream inputS;
private InputStream inBS;
private OutputStream outBS;

server = new ServerSocket(30501, 100);
clientSocket = server.accept();

public void getStreamFromClient()  {
    try {
        outBS = clientSocket.getOutputStream();
        outputS = new BufferedOutputStream( outBS);
        outputS.flush();

        inBS = clientSocket.getInputStream();
        inputS = new BufferedInputStream( inBS );

    } catch (Exception e) {
        e.printStackTrace();
    }
}

谢谢.

推荐答案

您遇到的问题与 TCP 流性质有关.

The problem you have is related to TCP streaming nature.

您从服务器发送 100 字节(例如)这一事实并不意味着您在第一次读取时会在客户端读取 100 字节.可能从服务器发送的字节在几个 TCP 段中到达客户端.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

您需要实现一个循环,在该循环中阅读直到收到整条消息.让我提供一个使用 DataInputStream 而不是 BufferedinputStream 的示例.很简单的事,给你举个例子.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

假设您事先知道服务器要发送 100 字节的数据.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

在客户端你需要写:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

现在,通常事先不知道一个节点(此处为服务器)发送的数据大小.然后你需要定义自己的小协议,用于服务器和客户端(或任何两个节点)之间的通信,使用 TCP 进行通信.

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

最常见最简单的就是定义TLV:Type、Length、Value.因此,您定义从服务器发送到客户端的每条消息都带有:

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 字节表示类型(例如,它也可以是 2 或其他).
  • 消息长度为 1 个字节(或其他)
  • 值的 N 字节(N 表示长度).

所以你知道你必须至少接收 2 个字节,并且通过第二个字节你知道你需要读取多少后续字节.

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

这只是一个可能的协议的建议.你也可以去掉Type".

This is just a suggestion of a possible protocol. You could also get rid of "Type".

所以应该是这样的:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

以下代码编译后看起来更好.它假定提供长度的前两个字节以二进制格式以网络字节序(大字节序)形式到达.没有关注消息其余部分的不同编码类型.

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

这篇关于如何读取服务器套接字 JAVA 中的所有 Inputstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何读取服务器套接字 JAVA 中的所有 Inputstream

基础教程推荐