Created
January 1, 2012 18:10
-
-
Save jordanorelli/1547943 to your computer and use it in GitHub Desktop.
websockets in Go.
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
<html> | |
<head> | |
<title>websockets</title> | |
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> | |
<script>$(function() { | |
var conn; | |
conn = new WebSocket("ws://localhost:8000/echo"); | |
conn.onopen = function(event) { | |
console.log("WebSocket Connected", event); | |
}; | |
conn.onclose = function(event) { | |
console.log("WebSocket closed", event); | |
}; | |
conn.onerror = function(event) { | |
console.log("WebSocket error", event); | |
}; | |
conn.onmessage = function(event) { | |
console.log("Received:", event.data); | |
$("#responses").append("<li>" + event.data + "</li>"); | |
}; | |
$("#requests").keydown(function(event) { | |
if(event.keyCode == 13){ | |
var text = $.trim($("#requests").val()); | |
if(text){ | |
conn.send(text); | |
$("#requests").val(""); | |
} | |
} | |
}); | |
});</script> | |
</head> | |
<body> | |
<ul id="responses"></ul> | |
<input id="requests" type="text" /> | |
</body> | |
</html> |
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
package main | |
import ( | |
"http" | |
"io" | |
"websocket" | |
) | |
func Home(w http.ResponseWriter, r *http.Request) { | |
http.ServeFile(w, r, "./index.html") | |
} | |
func Echo(ws *websocket.Conn) { | |
io.Copy(ws, ws) | |
} | |
func main() { | |
port := "0.0.0.0:8000" | |
http.HandleFunc("/", Home) | |
http.Handle("/echo", websocket.Handler(Echo)) | |
http.ListenAndServe(port, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment