golang基于websocket实现的简易聊天室程序
程序员文章站
2022-08-29 09:00:35
本文实例讲述了golang基于websocket实现的简易聊天室。分享给大家供大家参考,具体如下:
先说点无关的,最近忙于工作没有更新博客,今天休息顺便把golang w...
本文实例讲述了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="http://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())
}
}
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="http://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)
}
}
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语言程序设计有所帮助。
上一篇: 查询天气的服务引用,有类似的吧;
下一篇: 初步解读Golang中的接口相关编写方法
推荐阅读
-
微信小程序websocket聊天室的实现示例代码
-
express框架实现基于Websocket建立的简易聊天室
-
基于django channel实现websocket的聊天室的方法示例
-
php+html5基于websocket实现聊天室的方法
-
golang基于websocket实现的简易聊天室程序
-
.NET Core 基于Websocket的在线聊天室实现
-
荐 Java基于UDP的GUI界面简易聊天室课程实验(获取本机IP、IDEA同个程序运行两次设置方法)
-
Python基于Socket实现简易多人聊天室的示例代码
-
golang实现一个简单的websocket聊天室功能
-
php+html5基于websocket实现聊天室的方法_PHP