Go Socket 聊天室

  • 建立socket服务端 起一个服务
    1
    2
    3
    4
    5
    6
    7
       http.Handle("/",websocket.Handler(Server))

    err := http.ListenAndServe(":8080",nil)

    if err != nil {
    panic("ListendAndServer " + err.Error() )
    }
  • 建立客户端连接
    1
    2
    var ws = new WebSocket("ws://localhost:8080); //建立连接
    ws.send(data); //发送数据
  • 聊天室实现代码

    创建server监听tcp请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    package main

    import (
    "net/http"
    "code.google.com/p/go.net/websocket"
    "fmt"
    //"time"
    "time"
    )

    var userList = make(map[string]*websocket.Conn, 10)

    func Server(ws *websocket.Conn) {

    var err error
    userName := ws.Config().Location.Query().Get("userName")
    fmt.Println("user",userName)
    userList[userName] = ws



    for {
    var reply string

    if err = websocket.Message.Receive(ws, &reply); err != nil {
    fmt.Println("Can't receive")
    time.Sleep(time.Second * 10)
    }


    message := fmt.Sprintf("{\"user\":\"%s\",\"message\":\"%s\"}",userName,reply);
    fmt.Println(message)

    for _,v := range userList {
    if len(message) < 1 || message == "" {
    continue
    }
    if err = websocket.Message.Send(v, message); err != nil {
    fmt.Println("Can't send")
    continue
    }

    }
    }

    }

    func main() {
    http.Handle("/",websocket.Handler(Server))

    err := http.ListenAndServe(":8080",nil)

    if err != nil {
    panic("ListendAndServer " + err.Error() )
    }
    }

建立客户端页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Sample of websocket with golang</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

<script>
var userstr = [];

function generateMixed(n) {
var res = "";
for(var i = 0; i < n ; i ++) {
var id = Math.ceil(Math.random()*25);
res += userstr[id];
}
return res;
}


$(function () {
var ulDom = $('#msg-list');

for(var i=0;i<26;i++){
var temp = String.fromCharCode(97+i);
userstr.push(temp); //输出a-z 26个小写字母
}
//console.log(user);
var userName = generateMixed(8);
var sendInputDom = $('#send-value');
var ws = new WebSocket("ws://localhost:8080/chat?userName=" + userName);

ws.onmessage = function (e) {
var msg =JSON.parse(e.data);
if (msg.user == userName) {
var appendStr = '<li class="message-li"><span class="message-txt right">' + '' + msg.user + ': ' + msg.message + '</span></li>';
} else {
var appendStr = '<li class="message-li"><span class="message-txt">' + '' + msg.user + ': ' + msg.message + '</span></li>';
}
ulDom.append(appendStr);
console.log("接收到的内容 => " + e.data);
};

ws.onerror = function (e) {
console.log('onerror');
};
ws.onclose = function (e) {
console.log('close');
}

$('#sendBtn').click(function () {
sendMsg();
});

function sendMsg() {
var data = sendInputDom.val();
if (data == '') {
return false;
}
ws.send(data);
sendInputDom.val('');
}

document.onkeydown=function(event){
var e = event || window.event || arguments.callee.caller.arguments[0];
if(e && e.keyCode==13){ // enter 键
sendMsg();
}
};


});
</script>
<style>
*{
padding:0px;
margin:0px;

}
.send{
width: 100%;
height:80px;
background: #ddd;
overflow: hidden;
position: fixed;
bottom: 0px;

}
.warp{
width: 100%;
height: 100%;
}
.send-btn{
width: 80px;
height:50px;
padding: 10px 5px;
background: #0e90d2;
border: 1px solid #0e90d2;
border-radius: 5px ;
color: #ffffff;
font-size: 16px;
}
.input{
width: 60%;
min-width: 180px;
max-width: 550px;
height: 50px;
border-radius: 5px;
}
.content{
width: 80%;
margin: 0 auto;
padding: 10px 0px ;
}
.message-txt{
height: 30px;
line-height: 30px;
background: #ddd;
border-radius: 5px;
padding: 6px 15px;
}
.message-li{
margin: 15px ;
float: left;
display: block;
width: 95%;
}
.right{
float: right;
background: #0e90d2;
}
</style>
</head>
<body>

<div class="warp">

<ul id="msg-list">

</ul>

<div class="send">
<div class="content">
<input id="send-value" class="input" type="text"/>
<input type="button" id="sendBtn" value="send" class="send-btn"/>
</div>
</div>
</div>


</body>
</html>