Last active
May 11, 2017 12:00
-
-
Save SLonger/a0a40c773a6f3bf4a6e414bb01c45790 to your computer and use it in GitHub Desktop.
fork from : http://bl.ocks.org/tmichel/7390690
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
<html> | |
<head> | |
<title>WebSocket demo</title> | |
</head> | |
<body> | |
<div> | |
<form> | |
<label for="numberfield">Number</label> | |
<input type="text" id="numberfield" placeholder="12"/><br /> | |
<button type="button" id="sendBtn">Send</button> | |
</form> | |
</div> | |
<div id="container"></div> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> | |
<script type="text/javascript"> | |
$(function () { | |
var ws; | |
if (window.WebSocket === undefined) { | |
$("#container").append("Your browser does not support WebSockets"); | |
return; | |
} else { | |
ws = initWS(); | |
} | |
function initWS() { | |
var socket = new WebSocket("ws://192.168.1.166:8080/ws"), | |
container = $("#container") | |
socket.onopen = function() { | |
container.append("<p>Socket is open</p>"); | |
}; | |
socket.onmessage = function (e) { | |
container.append("<p> Got some shit:" + e.data + "</p>"); | |
} | |
socket.onclose = function () { | |
container.append("<p>Socket closed</p>"); | |
} | |
return socket; | |
} | |
$("#sendBtn").click(function (e) { | |
e.preventDefault(); | |
ws.send(12); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
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 ( | |
"fmt" | |
"github.com/gorilla/websocket" | |
"net/http" | |
"time" | |
) | |
func main() { | |
http.HandleFunc("/ws", wsHandler) | |
http.ListenAndServe("192.168.1.166:8080", nil) | |
} | |
var upgrader = websocket.Upgrader{ | |
ReadBufferSize: 1024, | |
WriteBufferSize: 1024, | |
CheckOrigin: func(r *http.Request) bool { return true }, | |
} | |
func wsHandler(w http.ResponseWriter, r *http.Request) { | |
conn, err := upgrader.Upgrade(w, r, nil) | |
if err != nil { | |
fmt.Println("websocket error") | |
http.Error(w, "Could not open websocket connection", http.StatusBadRequest) | |
} | |
go echo(conn) | |
} | |
func echo(conn *websocket.Conn) { | |
p := []byte("12") | |
message := 1 | |
timer := time.NewTicker(5 * time.Second) | |
for { | |
<-timer.C | |
if err := conn.WriteMessage(message, p); err != nil { | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment