网站地图    收藏   

主页 > 后端 > Golang >

golang基于websocket实现的简易聊天室程序

来源:自学PHP网    时间:2019-08-07 16:47 作者:小飞侠 阅读:

[导读] golang基于websocket实现的简易聊天室程序...

本文实例讲述了golang基于websocket实现的简易聊天室。分享给大家供大家参考,具体如下:

先说点无关的,最近忙于工作没有更新博客,今天休息顺便把golang websocket研究了一下,挺好玩的,写了一个聊天室,分享给大家.

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 := `


   
    golang websocket chatroom
   
   


   

   

   

       

           
       

   


`
    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)
    }
}

希望本文所述对大家Go语言程序设计有所帮助。

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论