EventSource Wrapper

Monkey Forums/User Modules/EventSource Wrapper

k.o.g.(Posted 2016) [#1]
** 18.05.2016 **
[CHANGED] Name of Subscribe / Unsubscribe to On / Off
[ADDED] Custom Events

** 18.05.2016 **
Initial Release




Hello

I'm presenting a little module for using EventSource on all Targets, which supports brl.socket and the HTML5 Target

Here you got some infos about EventSource:
http://www.html5rocks.com/en/tutorials/eventsource/basics/

Custom Events are not supported.

Currently is nothing documented and only tested Platforms are:
HTML5, iOS, Stdcpp, GLFW(3)

For Android i need a Milliseconds function and then i will test it. Have fun with using, maybe i will update some days the code.

interfaces.monkey


eventsource.monkey


demo.monkey
' 2016 Benjamin 'k.o.g.' Aregger
Strict

#If TARGET <> "stdcpp" Then
Import mojo
#End
Import brl.asyncevent
Import eventsource

Class Listener Implements IOnEventSourceMessage, IOnEventSourceEventMessage, IOnEventSourceOpen, IOnEventSourceError
	Method OnEventSourceOpen:Void(source:IEventSource)
		Print "Open"
		Print source.ReadyState
	End
	
	Method OnEventSourceError:Void(source:IEventSource)
		Print "Error"
		Print source.ReadyState
	End
	
	Method OnEventSourceMessage:Void(source:IEventSource, message:String , id:String = "")
		Print "Message"
		Print source.ReadyState
		Print message
	End
	
	Method OnEventSourceEventMessage:Void(source:IEventSource, event:String, message:String, id:String = "")
		Print "Custom Event: "+event
		Print source.ReadyState
		Print message
	End
End

Const URL:String = "http://reallocalhost:8888/tests/eventsource/test.php?blabla#asd"

#If TARGET <> "stdcpp" Then
	
	Class TestApp Extends App
		Field _source:EventSource
		
		Method OnCreate:Int()
			SetUpdateRate(60)
			
			Local listener:Listener = New Listener()
			
			_source = New EventSource(URL)
			_source.OnOpen = listener
			_source.OnMessage = listener
			_source.OnError = listener
			
			_source.On("test", listener)
			
			Print "Connecting"
			Print _source.ReadyState
			
			Return 0
		End
		
		Method OnUpdate:Int()
			UpdateAsyncEvents()
			Return 0
		End
		Method OnRender:Int()
			Cls(0, 0, 0)
			DrawText(Millisecs(), DeviceWidth() / 2, DeviceHeight() / 2, 0.5, 0.5)
			Return 0
		End
	End
	
	Function Main:Int()
		New TestApp()
		Return 0
	End

#Else

Extern Private
#If HOST = "winnt" Then
	Function usleep:Void(ms:Int) = "::Sleep"
#Else
	Function usleep:Void(ms:Int)
#End
	
Private
	
	Function Sleep:Void(ms:Int)
		usleep(ms)
	End

Public

	Function Main:Int()
		Local listener:Listener = New Listener()
		
		Local source:EventSource = New EventSource(URL)
		
		Print "Connecting"
		Print source.ReadyState
		
		source.OnOpen = listener
		source.OnMessage = listener
		source.OnError = listener
		
		source.On("test", listener)
		
		While True
			UpdateAsyncEvents()
			
			Sleep(1000)
		Wend
		Return 0
	End
	
#End