java - 通过套接字连续传输数据

标签 java sockets tcp

假设我有一个套接字,需要以随机(但很小)的间隔发送连续数据,假设每秒大约 20 个对象,无论时间跨度如何。

我预见到可能出现的问题,但我不知道如何处理。

1) 如果我像示例 A 那样一次发送一个对象,它们是否仍会成堆到达?以便更好地执行示例 B 中的操作?

2)接收数据的线程是否可能会在发送整个对象之前尝试读取数据,从而分割数据,并产生另一个我必须注意的问题?

发送数据的伪代码可能如下所示

示例A

void run()
{
    get socket outputstream
    while (isBroadcasting)
    {
        if (myQueue.isEmpty() == false)
            send first object in queue through outputstream

        Thread.sleep(25);
    }
}

示例 B

void run()
{
    get socket outputstream
    while (isBroadcasting)
    {
        while (myQueue.isEmpty() == false)
            send all object in queue through outputstream

        Thread.sleep(25);
    }
}

最后是这样读的

void run()
{
    get socket inputstream
    while (isReceiving)
    {
        get object(s) from inputstream and publish them to main thread

        Thread.sleep(25);
    }
}

3) 这是一个可行的解决方案吗?是否可以保持流在两端打开,循环并写入/读取数据直到完成?

最佳答案

1) If I send one object at a time as in example A, may they still arrive in bunches? So as to make it better to do as in example B?

根据您发送它们的网络类型,它们肯定仍然成群地到达接收端。另外,如果您使用的是TCP,则应用Nagle's algorithm可能会引入更多的聚集和明显的延迟。

2) Would the thread receiving the data possibly try to read the data before a entire object was sent, thus splitting data, and making another issue I will have to look out for?

这很大程度上取决于您的实现细节,并且无法用提供的伪代码来回答。

Is it ok to keep the streams open at both ends, looping and writing/reading data until finished?

是的,长时间使用这样的 TCP 连接是完全合理的。但是,如果由于某种原因连接丢失,您的应用程序必须愿意重新连接。

关于java - 通过套接字连续传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16754958/

相关文章:

java - 有没有办法用 JList 获取垂直索引?

Java:在arraylist中存储扩展对象并调用parent toString方法

c - 如何使用 getaddrinfo 连接到使用外部 IP 的服务器?

python - 如何在同一 .py 中但在不同端口上对客户端和服务器进行多线程处理

JAVA TCP 服务器错误

tcp - 如何将 lwIP tcp/ip 堆栈与微 Controller stm32f4(客户端)一起使用

Java递归根函数

java - Spring 集成和响应式(Reactive) WebSockets

javascript - 使用 append() 添加元素并设置其 id

python - 持续监听TCP端口