zoukankan      html  css  js  c++  java
  • golang 聊天室

    近期看了一些关于golang的资料。发现它的WEBSOCKT实现真起来真的非常easy。以下是代码

    go.net/websocket是须要安装的,这个自己装上即可

    package main
    
    
    import (
        "container/list"
        "fmt"
        "go.net/websocket"
        "io"
        "net/http"
    )
    
    
    var connid int
    var conns *list.List
    
    
    func Chat(ws *websocket.Conn) {
        defer ws.Close()
        item := conns.PushBack(ws)
        defer conns.Remove(item)
    
    
        var err error
        for {
            var data string
            if err = websocket.Message.Receive(ws, &data); err != nil {
                fmt.Printf("disconnected
    ")
                break
            }
    
    
            SendMessage(item, fmt.Sprintf("%s", data))
        }
    }
    
    
    func SendMessage(self *list.Element, data string) {
        //for _, item := range conns {
        for item := conns.Front(); item != nil; item = item.Next() {
            ws, ok := item.Value.(*websocket.Conn)
            if !ok {
                panic("item not *websocket.Conn")
            }
    
    
            if item == self {
                continue
            }
    
    
            io.WriteString(ws, data)
        }
    }
    
    
    // client默认显示页面
    func Client(w http.ResponseWriter, r *http.Request) {
        html := `<!doctype html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>golang websocket chatroom</title>
        <script language="javascript"type="text/javascript">  
            var sock=null; 
            var wsuri ="ws://192.168.1.163:7878/chat"; //这里的IP假设是局域測试的话。须要换成自己的
            window.onload = function(){
                console.log("onload");
                sock = new WebSocket(wsuri);
                sock.onopen=function(e){
                    console.log("connected to "+wsuri);
                }
                sock.onclose=function(e){
                    console.log("connection closed (" + e.code + ")");
                }
                sock.onmessage=function(e){
                    console.log("message received: " + e.data);
                    document.getElementById("list").innerHTML += e.data;
                    var div = document.getElementById("list")
                    div.scrollTop = div.scrollHeight; 
                }
            }
            function send () {
                var who = document.getElementById('who').value;
                if (who.length == 0){
                    document.getElementById('who').focus();
                    return
                }
                var msg = document.getElementById('msg').value;
                if (msg.length == 0){
                    document.getElementById('msg').focus();
                    return
                }
                var data = who + "  say:  " + msg + "<br/><br/>";
                document.getElementById('msg').value="";
                document.getElementById('who').value="";
                var div = document.getElementById("list")
                div.innerHTML += data;
                div.scrollTop = div.scrollHeight; 
                sock.send(data);
            }        
        </script>
    </head>
    <body>
        <div id="list" style="height: 300px;overflow-y: scroll;border: 1px solid #CCC;">
        </div>
        <div>
            who are you 
            <input type="text" id="who" size="60" />
            your message
            <input type="text" id="msg" size="60" />
    
    
            <button onclick="send()">send</button>
        </div>
    </body>
    </html>`
        io.WriteString(w, html)
    }
    
    
    func main() {
        conns = list.New()
    
    
        http.Handle("/chat", websocket.Handler(Chat))
        http.HandleFunc("/", Client)
        err := http.ListenAndServe(":7878", nil)
        if err != nil {
            panic("ListenAndServe: " + err.Error())
        }
    }
    
    

  • 相关阅读:
    javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp
    Java 向上造型
    java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=testUpdate], {ExactMatcher:fDisplayName=testUpdate(com.zjf.spring.jdbc.JDBCTest)],
    The prefix "p" for attribute "p:message" associated with an element type "bean"
    SVN the working copy needs to be upgraded svn
    Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/cx f/tools/wsdlto/WSDLToJava : Unsupported major.minor version 52.0
    git 403
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '[<_UIFeedbackParameters 0x1d4442e50> setNilValueForKey]: could not set nil as the value for the key rate.'
    Xcode无法退出,报错提示 The document “xxx.h” could not be saved. The file doesn’t exist.
    iOS打包上传ipa文件时,报错<ERROR ITMS-90096: "Your binary is not optimized for iPhone 5
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/7283156.html
Copyright © 2011-2022 走看看