Skip to content

Instantly share code, notes, and snippets.

@farnoy
Created February 12, 2012 10:38
Show Gist options
  • Save farnoy/1807808 to your computer and use it in GitHub Desktop.
Save farnoy/1807808 to your computer and use it in GitHub Desktop.
golang websockets
package main
import (
"websocket"
"http"
"fmt"
"io"
)
func EchoServer(ws *websocket.Conn) {
msg := make([]byte, 50)
n, _ := ws.Read(msg)
fmt.Println("got:", string(msg[:n]))
io.Copy(ws, ws)
}
func main() {
http.Handle("/echo", websocket.Handler(EchoServer))
err := http.ListenAndServe(":8082", nil)
if err != nil {
panic(err.String())
}
}
<!DOCTYPE html>
<html>
<head>
<title>Socket test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<style type="text/css">
div#items { background: #CCC; }
div#item {background: aqua; }
</style>
</head>
<body>
<h1>Socket test</h1>
<div id="items"></div>
<script type="text/javascript">
try {
var Socket = new WebSocket("ws://localhost:8082/echo");
Socket.onopen = function() { console.log("Socket opened");Socket.send("0 5"); }
Socket.onmessage = function(data) { $("#items").append('<div id="item">' + data + '</div>'); }
} catch(exception) {
console.log(exception);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment