Golang Simple Chat Room program based on websocket implementation _golang

Source: Internet
Author: User
Tags sprintf

This article illustrates a simple chat room based on the websocket implementation of Golang. Share to everyone for your reference, specific as follows:

First of all, it is irrelevant, recently busy work did not update the blog, today rest by the way Golang WebSocket studied a bit, quite fun, wrote a chat room, to share with you.

WebSocket Bag: Code.google.com/p/go.net/websocket

Documents: Http://go.pkgdoc.org/code.google.com/p/go.net/websocket

First install the WebSocket package

Copy Code code as follows:
Go to Code.google.com/p/go.net/websocket

Down is the chat room code, hehe

Golang websocket Chat Room

Copy Code code as follows:
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)
}
}
Web Client
Func Client (w http. Responsewriter, R *http. Request) {
HTML: = ' <!doctype html>
<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>
<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= "/>"
</form>
</div>
</body>
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 ())
}
}

It's a little rough, but there's a basic function.

Golang WebSocket Client

Copy Code code as follows:
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)
}
}

I hope this article will help you with your go language program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.