我正在编写一个需要EventSource
接收服务器发送事件的 Android 应用程序。我正在尝试创建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();
}