本文实例讲述了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 := `<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>golang websocket chatroom</title>
<script src="/UploadFiles/2021-04-08/jquery.min.js">
<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)
}
}
希望本文所述对大家Go语言程序设计有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 黄乙玲1988-无稳定的爱心肝乱糟糟[日本东芝1M版][WAV+CUE]
- 群星《我们的歌第六季 第3期》[320K/MP3][70.68MB]
- 群星《我们的歌第六季 第3期》[FLAC/分轨][369.48MB]
- 群星《燃!沙排少女 影视原声带》[320K/MP3][175.61MB]
- 乱斗海盗瞎6胜卡组推荐一览 深暗领域乱斗海盗瞎卡组分享
- 炉石传说乱斗6胜卡组分享一览 深暗领域乱斗6胜卡组代码推荐
- 炉石传说乱斗本周卡组合集 乱斗模式卡组最新推荐
- 佟妍.2015-七窍玲珑心【万马旦】【WAV+CUE】
- 叶振棠陈晓慧.1986-龙的心·俘虏你(2006复黑限量版)【永恒】【WAV+CUE】
- 陈慧琳.1998-爱我不爱(国)【福茂】【WAV+CUE】
- 咪咕快游豪礼放送,百元京东卡、海量欢乐豆就在咪咕咪粉节!
- 双11百吋大屏焕新“热”,海信AI画质电视成最大赢家
- 海信电视E8N Ultra:真正的百吋,不止是大!
- 曾庆瑜1990-曾庆瑜历年精选[派森][WAV+CUE]
- 叶玉卿1999-深情之选[飞图][WAV+CUE]