分隔来自套接字的数据 [英] Delimit data coming from socket

查看:143
本文介绍了分隔来自套接字的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java应用程序中,有一个Socket打开,正在从其InputStream中读取数据。

In my Java application there is a Socket open and data is being read from its InputStream.

在最佳条件下,每个进入的数据包都会导致调用read()返回其应用程序层数据。这就是我想要获得的 - 每个数据包一个'消息'

In optimal conditions each packet that comes in results in a call to read() returning its application layer data. This is what I am trying to get - one 'message' per packet.

然而,数据可能会在套接字中缓冲基于getReceiveBufferSize()返回的内容。如果发生这种情况并且从中读取流,则可能存在来自多个数据包的数据。

However, it is possible that data gets buffered in the socket based on what getReceiveBufferSize() returns. If this happens and the stream is read from, there may be data from multiple packets sitting there.

是否有另一种从单个数据包中获取数据的方法,或者这是否违反了抽象层?
或者,是否可以为数据添加到缓冲区时设置某种分隔符?或者是平台级别的东西无法完成?

Is there another method to get data from individual packets, or does that violate layers of abstraction? Alternatively, is it possible to set some sort of delimiter for when data gets appended to the buffer? Or is that something at the platform level that cannot be done?

以下是一些示例代码来演示我在做什么:

Here is some example code to demonstrate what I am doing:

import java.io.InputStream;
import java.net.Socket;

public class Belnets {


public Belnets() {
    try{
        Socket s = new Socket("address", 23);
        System.out.println("platform will buffer this much: "+s.getReceiveBufferSize());
        InputStream sin = s.getInputStream();
        byte[] data = new byte[1024];
        int c;
        while(true){
            c = sin.read(data);
            for(int i=0; i<c; i++){
                System.out.print((char)data[i]);
            }
            System.out.println("=END OF READ=");

            //if you dont do this, read() seems to return once for each packet as this loop 
            //appears to be running fast enough to keep up with the rate of data that comes in.
            //otherwise data gets buffered and you get multiple packets worth of data before seeing
            //=END OF READ=
            Thread.sleep(1000);     

        }

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



public static void main(String args[]){
    new Belnets();
}

}


推荐答案

Java API不提供任何读取TCP数据包的方法。它是基于流的,你绝对无法一次读取一个数据包。

The Java API doesn't provide any way to read TCP packets. It's stream-based, and you have absolutely no way to read one packet at a time.

如果要发送和接收多条消息,则需要实现应用程序级协议,该协议可能使用消息之间的特定分隔符,或者发送长度为a消息正文本身后面跟着消息,例如。

If you want to send and receive multiple messages, you need to implement an application-level protocol, which might use a specific delimiter between messages, or send the length of a message followed by the message body itself, for example.

这篇关于分隔来自套接字的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆