Last active
March 20, 2018 09:28
-
-
Save riyafa/df10a5a130593d87038d3e92139fb863 to your computer and use it in GitHub Desktop.
Compiling websocket code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ballerina.net.http; | |
import ballerina.io; | |
import ballerina.runtime; | |
endpoint http:ServiceEndpoint ep1 { | |
port:9090 | |
}; | |
@http:WebSocketServiceConfig { | |
basePath:"/basic/ws" | |
} | |
service<http: WebSocketService > hello bind ep1{ | |
string ping = "ping"; | |
blob pingData = ping.toBlob("UTF-8"); | |
onUpgrade ( endpoint conn, http:Request req) { | |
io: println("\nNew client hello"); | |
conn->upgradeToWebSocket({"some":"world"}); | |
//conn->cancelUpgradeToWebSocket(1001, "Sorry leaving"); | |
} | |
onOpen ( endpoint conn) { | |
io: println("\nNew client connected"); | |
} | |
onTextMessage ( endpoint conn, http:TextFrame frame) { | |
io: println("\ntext message: " + frame. text + " & is final fragment: " + frame. isFinalFragment); | |
string text = frame.text; | |
if (text == "ping") { | |
io:println("Pinging..."); | |
conn->ping( pingData); | |
} else if (text == "closeMe") { | |
conn->closeConnection(1001, "You asked me to close connection"); | |
} else { | |
conn->pushText("You said: " + frame.text); | |
} | |
} | |
onBinaryMessage(endpoint conn, http:BinaryFrame frame) { | |
io: println("\nNew binary message received"); | |
blob b = frame.data; | |
io: println("UTF-8 decoded binary message: " + b. toString("UTF-8")); | |
conn-> pushBinary(b); | |
} | |
onPing(endpoint conn, http:PingFrame frame) { | |
conn-> pong(frame. data); | |
} | |
onPong( endpoint conn, http:PongFrame frame) { | |
io: println("Pong received"); | |
} | |
onIdleTimeout( endpoint conn) { | |
io: println("\nReached idle timeout"); | |
io: println("Closing connection "); | |
conn-> closeConnection(1001, "Connection timeout"); | |
} | |
onClose( endpoint conn, http:CloseFrame closeFrame) { | |
io: println("\nClient left with status code " + closeFrame. statusCode + " because " + closeFrame. reason); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working code: