美文网首页
WebSocket Helloworld!

WebSocket Helloworld!

作者: 何约什 | 来源:发表于2018-06-14 20:43 被阅读136次

    看了别人用C#写的Hello world,我用go语言写了一个版本。

    服务端代码

    package main
    import (
    "net/http"
    "github.com/gorilla/websocket"
    "fmt"
    )
    func main() {
    staticFileHandler := http.FileServer(http.Dir("src/herry2038.org/websocket/static"))
    var siteMux = http.NewServeMux()
    siteMux.Handle("/", http.StripPrefix("/", staticFileHandler))
    http.Handle("/", http.Handler(siteMux))
    http.Handle("/ws", generateHandleWS())
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
    panic("ListenAndServe: " + err.Error())
    }
    }
    func generateHandleWS() http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("New client connected: %s", r.RemoteAddr)
    if r.Method != "GET" {
    http.Error(w, "Method not allowed", 405)
    return
    }
    upgrader := &websocket.Upgrader{
    ReadBufferSize: 1024,
    WriteBufferSize: 1024,
    Subprotocols: []string{"test"},
    CheckOrigin: nil,
    }
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
    fmt.Printf("closed %v", err)
    return
    }
    defer conn.Close()
    processWSConn(conn)
    }
    }
    func processWSConn(conn *websocket.Conn) {
    for {
    typ, msg, err := conn.ReadMessage()
    if err != nil {
    fmt.Printf("receive message failed:%v", err)
    return
    }
    if typ != websocket.TextMessage {
    continue
    }
    fmt.Printf("received a msg:%s\n", string(msg))
    backMsg := "hello:" + string(msg)
    conn.WriteMessage(websocket.TextMessage, []byte(backMsg))
    }
    }

    客户端代码

    <html>
    <meta charset="utf-8" />
    <title>WebSocket Test</title>
    <script language="javascript" type="text/javascript">
    var wsUri = "ws://127.0.0.1:8080/ws";
    var output;
    function init() {
    output = document.getElementById("output");
    testWebSocket();
    }
    function testWebSocket() {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function (evt) { onOpen(evt) };
    websocket.onclose = function (evt) { onClose(evt) };
    websocket.onmessage = function (evt) { onMessage(evt) };
    websocket.onerror = function (evt) { onError(evt) };
    } function onOpen(evt) {
    writeToScreen("CONNECTED");
    }
    function onClose(evt) { writeToScreen("DISCONNECTED"); }
    function onMessage(evt) { document.getElementById('result').value = evt.data; }
    function onError(evt) { writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); }
    function doSend(message) { websocket.send(message); }
    function writeToScreen(message) {
    var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.insertBefore(pre);
    }
    function OnConnect() {
    wsUri = document.getElementById("url").value;
    init();
    }
    </script>
    <body>
    <fieldset>
    <legend>WebSocket hello wold</legend>
    <p><span>Server url:</span><input id="url" type="text" value="ws://127.0.0.1:8080/ws"/><input type="button" value="Connected" onclick="OnConnect()" /></p>
    <p><span>Enter you name:</span><input id="youname" type="text" value="test"/><input type="button" value="Submit" onclick="doSend(document.getElementById('youname').value)" /></p>
    <p><span>Result:</span><input id="result" type="text" value=""/></p>
    </fieldset>
    <div id="output">
    </div>
    </body>
    </html>

    运行效果

    运行效果.png

    相关文章

      网友评论

          本文标题:WebSocket Helloworld!

          本文链接:https://www.haomeiwen.com/subject/qkdueftx.html