0
我正在編寫一個Android應用程序,需要EventSource
才能接收服務器發送的事件。我正在嘗試創建SseEventSourceFactory
對象,但創建時會出現NoSuchElement
異常。我怎樣才能解決這個問題?爲Android實現Kaazing EventSource
這裏是我的代碼:
// 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();
}