java - 为 Android 实现 Kaazing EventSource

标签 java php android eventsource kaazing

我正在编写一个 Android 应用程序,需要 EventSource 来接收服务器发送的事件。我正在尝试创建 SseEventSourceFactory 对象,但在创建时出现 NoSuchElement 异常。我该如何解决这个问题?

这是我的代码:

// Import java.net classes
import java.net.URI;
import java.net.URL;

// Import EventSource API classes
import com.kaazing.net.sse.SseEventReader;
import com.kaazing.net.sse.SseEventSource;
import com.kaazing.net.sse.SseEventSourceFactory;
import com.kaazing.net.sse.SseEventType;

try {
            // Create Event Source factory( Exception thrown here
            SseEventSourceFactory factory = SseEventSourceFactory.createEventSourceFactory();

            // Create a target location using the java.net.URI create() method
            final SseEventSource es = factory.createEventSource(URI.create("http://cak9c.com/sse.php"));

            // Connect to the event source.
            es.connect();

            final Object o = this;
            Thread sseEventReaderThread = new Thread() {
                public void run() {
                    try {
                        SseEventReader reader = es.getEventReader(); // Receive event stream

                        SseEventType type = null;
                        while ((type = reader.next()) != SseEventType.EOS) { // Wait until type is DATA
                            switch (type) {
                                case DATA:
                                    // Return the payload of the last received event
                                    System.out.println(reader.getData());
                                    break;
                                case EMPTY:
                                    System.out.println("no data");
                                    break;
                            }
                        }

                    }
                    catch (Exception ex) {
                        System.out.println(ex.getMessage());
                    }
                }
            };
            es.close();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
            Toast.makeText(this, e.getLocalizedMessage() + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
        }

最佳答案

请使用此 PHP 代码:

<?php

$tickets = [
    [ "GOOG", 533.37 ],
    [ "MSFT",  47.59 ],
    [ "IBM",  162.99 ],
    [ "AAPL", 114.12 ],
    [ "MSFT",  47.29 ],
];

$ticketsLength = count($tickets);

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");

$lastId = 0;

// Check that lastId is not larger than the size of array - if it is larger star from zero.
if ($lastId >= $ticketsLength) {
    $lastId = 0;
}

while (true) {

    sendMessage($lastId, $tickets[$lastId][0], $tickets[$lastId][1]);
    $lastId++;

    // Check that lastId is not larger than the size of array - if it is larger close connection.
    if ($lastId >= $ticketsLength) {
        die();
    }
    sleep(1);
}


function sendMessage($id, $ticket, $price) {
    echo "id: $id\n";
    echo "data: $ticket:$price\n\n";
    ob_flush();
    flush();
}

?>

将以下库添加到 Android Studio 项目:

com.kaazing.gateway.client.android.jar
com.kaazing.gateway.jms.client.android.jar
com.kaazing.gateway.jms.client.android-javadoc.jar

并使用此 Java Android 代码(根据需要更改 IP 地址)

import java.net.URI;
import com.kaazing.net.sse.SseEventReader;
import com.kaazing.net.sse.SseEventSource;
import com.kaazing.net.sse.SseEventSourceFactory;
import com.kaazing.net.sse.SseEventType;


/* 
...

*/


  Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Thread thread = new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try {
                            SseEventSourceFactory factory = SseEventSourceFactory.createEventSourceFactory();
                            final SseEventSource es = factory.createEventSource(URI.create("http://10.2.56.21/demo.php"));
                            es.connect();
                            SseEventReader reader = es.getEventReader(); // Receive event stream

                            SseEventType type = null;
                            while ((type = reader.next()) != SseEventType.EOS) { // Wait until type is DATA
                                switch (type) {
                                    case DATA:
                                        // Return the payload of the last received event
                                        Log.e("SOME_TAG", (String) reader.getData());
                                        break;
                                    case EMPTY:
                                        Log.e("SOME_TAG", "no data");
                                        break;
                                }

                            }

                         }

                         catch(Exception e)
                          {
                                Log.e("SOME_TAG", e.getMessage());

                            }
                        }

                    });

            thread.start();

            }
        });

您应该得到如下所示的控制台输出:

id: 0
data: GOOG:533.37

id: 1
data: MSFT:47.59

id: 2
data: IBM:162.99

关于java - 为 Android 实现 Kaazing EventSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38227464/

相关文章:

javascript - 如何在 webview 中加载完整的谷歌图书网址?

java - 如何创造更真实的爆炸

java - 在业务逻辑中访问应用程序上下文实例时出现 NullPointerException。如何访问应用程序上下文的实例?

php - 上传文件到Web服务器错误6 php

php - .htaccess 将动态 url 段添加到现有重写规则

android - 程序类型已存在 : android. support.v4.media.MediaBrowserCompat$CustomActionCallback

java - clone() : ArrayList. clone() 我以为做了浅拷贝

java - 斯坦福 NLP 分类器示例

java - 如何在本地无线网络中的两部手机之间传输数据进行测试?

PHP 上传大图像并按比例调整大小,如 Photoshop