Skip to content

Instantly share code, notes, and snippets.

@riyafa
Last active March 20, 2018 09:28
Show Gist options
  • Save riyafa/df10a5a130593d87038d3e92139fb863 to your computer and use it in GitHub Desktop.
Save riyafa/df10a5a130593d87038d3e92139fb863 to your computer and use it in GitHub Desktop.
Compiling websocket code
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);
}
}
@riyafa
Copy link
Author

riyafa commented Mar 11, 2018

Working code:

var ws = new WebSocket("ws://localhost:9090/basic/ws");
ws.onmessage = function(frame) {console.log(frame.data)};
ws.onclose = function(frame) {console.log(frame)};
ws.send("hello world");
ws.send("ping");
ws.close(1000, "I want to go");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment