Created
February 12, 2012 10:38
-
-
Save farnoy/1807808 to your computer and use it in GitHub Desktop.
golang websockets
This file contains 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
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()) | |
} | |
} |
This file contains 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
<!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