返回顶部

收藏

用Go语言实现一个简单的聊天室程序

更多

websocket包 : code.google.com;/p/go.net/websocket

文档 : http;://go.pkgdoc.org/code.google.com/p/go.net/websocket

首先安装websocket包

go get; code.google.com;/p/go.net/websocket 下来就是聊天室代码了,呵呵

golang websocket; 聊天室

package main

import (
    "fmt"
    "io"
    "bufio"
    "net/http"
    "code.google.com/p/go.net/websocket"
    "container/list"
)

var connid int
var conns *list.List

func ChatroomServer(ws *websocket.Conn) {
    defer ws.Close()

    connid++
    id := connid

    fmt.Printf("connection id: %d\n", id)

    item := conns.PushBack(ws)
    defer conns.Remove(item)

    name := fmt.Sprintf("user%d", id)

    SendMessage(nil, fmt.Sprintf("welcome %s join\n", name))

    r := bufio.NewReader(ws)

    for {
        data, err := r.ReadBytes('\n')
        if err != nil {
            fmt.Printf("disconnected id: %d\n", id)
            SendMessage(item, fmt.Sprintf("%s offline\n", name))
            break
        }

        fmt.Printf("%s: %s", name, data)

        SendMessage(item, fmt.Sprintf("%s\t> %s", name, 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)
    }
}

                                // 网页客户端
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 src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        var ws = new WebSocket("ws://127.0.0.1:6611/chatroom");
        ws.onopen = function(e){
            console.log("onopen");
            console.dir(e);
        };
        ws.onmessage = function(e){
            console.log("onmessage");
            console.dir(e);
            $('#log').append('<p>'+e.data+'<p>');
            $('#log').get(0).scrollTop = $('#log').get(0).scrollHeight;
        };
        ws.onclose = function(e){
            console.log("onclose");
            console.dir(e);
        };
        ws.onerror = function(e){
            console.log("onerror");
            console.dir(e);
        };
        $(function(){
            $('#msgform').submit(function(){
                ws.send($('#msg').val()+"\n");
                $('#log').append('<p style="color:red;">My > '+$('#msg').val()+'<p>');
                $('#log').get(0).scrollTop = $('#log').get(0).scrollHeight;
                $('#msg').val('');
                return false;
            });
        });
    </script>
</head>
<body>
    <div id="log" style="height: 300px;overflow-y: scroll;border: 1px solid #CCC;">
    </div>
    <div>
        <form id="msgform">
            <input type="text" id="msg" size="60" />
        </form>
    </div>
</body>
</html>`
    io.WriteString(w, html)
}

func main() {
    fmt.Printf(`Welcome chatroom server!
author: dotcoo zhao
url: http://www.dotcoo.com/golang-websocket-chatroom

`)

    connid = 0
    conns = list.New()

    http.Handle("/chatroom", websocket.Handler(ChatroomServer));
    http.HandleFunc("/", Client);
    err := http.ListenAndServe(":6611", nil);
    if err != nil {
        panic("ListenAndServe: " + err.Error())
    }
}

简陋了些,但是基本功能都有了.

golang websocket; 客户端

package main

import (
    "fmt"
    "bufio"
    "io"
    "os"
    "code.google.com/p/go.net/websocket"
)

func Command(ws *websocket.Conn) {
    r := bufio.NewReader(os.Stdin)
    w := bufio.NewWriter(ws)

    for {
        data, err := r.ReadBytes('\n')
        if err != nil {
            panic(err)
        }

        _, err = w.Write(data)
        if err != nil {
            panic(err)
        }
        w.Flush()

        fmt.Printf("My\t> ")
    }
}

func main() {
    fmt.Printf(`Welcome chatroom!
author: dotcoo zhao
url: http://www.dotcoo.com/golang-websocket-chatroom

`)

    origin := "http://127.0.0.1:6611/"      
    url := "ws://127.0.0.1:6611/chatroom"

    ws, err := websocket.Dial(url, "", origin)
    if err != nil {
        panic(err)
    }
    defer ws.Close()

    r := bufio.NewReader(ws)
    //w := bufio.NewWriter(os.Stdout)

    go Command(ws)

    for {
        data, err := r.ReadBytes('\n')
        if err == io.EOF {
            fmt.Printf("disconnected\n")
            os.Exit(0)
        }
        if err != nil {
            panic(err)
        }

        fmt.Printf("\r%sMy\t> ", data)
    }
}

标签:聊天室,golang,websocket

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. musiXboy 发表 2013-03-15 00:22:00 读者投稿:Google Reader,忘不了你
  2. musiXboy 发表 2013-03-17 18:53:10 读者投稿:关闭 Google Reader 是作恶之举?
  3. Yuku 发表 2013-03-17 04:44:00 Honest Logos
  4. polaris 发表 2013-01-28 16:23:51 再看GOPATH
  5. noreply@blogger.com 发表 2011-10-04 23:18:00 Learn Go from your browser
  6. noreply@blogger.com 发表 2013-05-24 00:38:23 Advanced Go Concurrency Patterns
  7. 博主 发表 2012-12-10 16:00:00 Go 语言的错误处理机制
  8. gouki 发表 2013-09-03 23:13:00 using NGINX or not?
  9. the5fire 发表 2013-11-04 13:38:22 Go无框架开发Web应用
  10. polaris 发表 2014-02-08 03:50:56 Golang 代码中绑定Host
  11. 无闻 发表 2014-01-16 07:00:00 《Go编程基础》视频教程
  12. 博主 发表 2014-04-27 07:00:00 Go语言HTTP包浅谈(一)

发表评论