Skip to content

Commit

Permalink
修改BUG
Browse files Browse the repository at this point in the history
  • Loading branch information
xizhenhua committed Dec 13, 2017
1 parent 6a6fb88 commit 0377134
Show file tree
Hide file tree
Showing 3 changed files with 247 additions and 57 deletions.
103 changes: 74 additions & 29 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,15 @@ import (
)

const (
// Time allowed to write a message to the peer.
writeWait = 3 * time.Second
// 写消息允许的等待时间
writeWait = 10 * time.Second

// Time allowed to read the next pong message from the peer.
pongWait = 3 * time.Second
// 心跳允许的等待时间
pongWait = 60 * time.Second

// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10

// Maximum message size allowed from peer.
// 发送消息最大的字节数
maxMessageSize = 512
)

Expand All @@ -35,7 +34,7 @@ var upgrader = websocket.Upgrader{
WriteBufferSize: 1024,
}

// Client is a middleman between the websocket connection and the hub.
// 客户端
type Client struct {
hub *Hub

Expand All @@ -46,23 +45,46 @@ type Client struct {
send chan []byte

// uuid
uUID string
uuid string

// nickname
nickName string
}

// UserInfo 用户信息
type UserInfo struct {
UUID string
NickName string
Client *Client
}

// 待发送消息
type Broad struct {
Content []byte
Rtype int64
Client *Client
}

// Msg 消息体
type Msg struct {
Code int
Rtype int
From string
To string
Content string
Uids []string
User map[string]string
NowUID string
}

// 读取消息体
type ReadMsg struct {
Content string
FromNick string
MsgFrom string
MsgTo string
}

// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
// 读取消息
func (c *Client) readPump() {
defer func() {
c.hub.unregister <- c
Expand All @@ -82,21 +104,34 @@ func (c *Client) readPump() {
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
//写入消息
var msg Msg
var readMsg ReadMsg
msg.Code = 200
msg.Rtype = 1
msg.From = c.uuid
msg.Content = string(message)
json.Unmarshal([]byte(msg.Content), &readMsg)
msg.To = readMsg.MsgTo
msgJSON, err := json.Marshal(msg)
var broad Broad
broad.Content = msgJSON
if readMsg.MsgTo == "ALL" {
broad.Rtype = 1
} else {
broad.Rtype = 2
if _, ok := c.hub.userINFO[msg.To]; ok {
broad.Client = c.hub.userINFO[msg.To].Client
} else {
//
continue
}
}
if err == nil {
c.hub.broadcast <- msgJSON
c.hub.broadcast <- broad
}
}
}

// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
// 写消息
func (c *Client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
Expand Down Expand Up @@ -139,7 +174,7 @@ func (c *Client) writePump() {
}
}

// serveWs handles websocket requests from the peer.
// websocket服务架设
func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
Expand All @@ -149,25 +184,35 @@ func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client

//获取昵称
nickName := r.FormValue("nick")
client.nickName = nickName

//分配UUID
uid := uuid.NewV4().String()
client.uUID = uid
hub.uuids[client.uUID] = uid
client.uuid = uid

//构建用户实体
userInfo := &UserInfo{UUID: uid, NickName: nickName, Client: client}
hub.userINFO[uid] = userInfo

//实验阶段每次有人进入则把所有用户UUID发送到客户端
var msg Msg
for num := range hub.uuids {
msg.Uids = append(msg.Uids, num)
var users = make(map[string]string)
for _, vlue := range hub.userINFO {
users[vlue.UUID] = vlue.NickName
}
msg.User = users
msg.Code = 200
msg.Rtype = 2
msg.NowUID = uid
msgJSON, err := json.Marshal(msg)
var broad Broad
broad.Content = msgJSON
broad.Rtype = 1
if err == nil {
client.hub.broadcast <- msgJSON
client.hub.broadcast <- broad
}

// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump()
}
137 changes: 128 additions & 9 deletions home.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,115 @@
<html lang="en">
<head>
<title>Chat Example</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
var msgFrom;
var msgTo = "ALL";
var nickName ="";
var users = [];
window.onload = function () {
var conn;
var send = [];
var msg = document.getElementById("msg");
var log = document.getElementById("log");
var user = document.getElementById("user");
var ulist = document.getElementById("ulist");
var toText = document.getElementById("toText");

yourName = prompt("请输入你的名字:","");
if (yourName != null&&yourName != ""){
nickName =yourName;
}else{
alert("请刷新重新输入名字");
return;
}

function appendLog(item) {
var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
log.appendChild(item);
if (doScroll) {
log.scrollTop = log.scrollHeight - log.clientHeight;
}
}
function appendUser(item) {
var doScroll = user.scrollTop > user.scrollHeight - user.clientHeight - 1;
ulist.appendChild(item);
if (doScroll) {
user.scrollTop = user.scrollHeight - user.clientHeight;
}
}
document.getElementById("form").onsubmit = function () {
if (!conn) {
return false;
}
if (!msg.value) {
return false;
}
conn.send(msg.value);
//拼接字符串
send = {};
send.MsgFrom = msgFrom;
send.MsgTo = msgTo;
send.FromNick = nickName;
send.Content = msg.value;
sendJSON = JSON.stringify(send);
conn.send(sendJSON);
msg.value = "";

if(msgTo!="ALL"){
var item = document.createElement("div");
item.innerText = "你说: "+ send.Content;
appendLog(item);
}
return false;
};
if (window["WebSocket"]) {
conn = new WebSocket("ws://" + document.location.host + "/ws");
conn = new WebSocket("ws://" + document.location.host + "/ws?nick="+nickName);
conn.onclose = function (evt) {
var item = document.createElement("div");
item.innerHTML = "<b>Connection closed.</b>";
appendLog(item);
};
conn.onmessage = function (evt) {
var messages = evt.data.split('\n');
for (var i = 0; i < messages.length; i++) {
var item = document.createElement("div");
item.innerText = messages[i];
appendLog(item);
var messages = evt.data;
msgJSON = JSON.parse(messages);
if(msgJSON.Code==200){
if(msgJSON.Rtype==2){
//给当前用户赋值UUID
if(!msgFrom){
msgFrom = msgJSON.NowUID;
}
//加载用户列表
ulist.innerHTML ="";
users = [];
$.each(msgJSON.User,function(e,t){
var item = document.createElement("li");
item.innerText = t;
$(item).attr("uid",e);
usersJSON = {};
usersJSON.uid = e;
usersJSON.nick = t;
users.push(usersJSON);
item.addEventListener("click",function(){
var $wellToUid = $(this).attr("uid");
if($wellToUid==msgFrom){
alert('不能给自己发送消息');
}
msgTo = $wellToUid;
toText.innerText = this.innerText;
})
appendUser(item);
})
}
if(msgJSON.Rtype==1){
var item = document.createElement("div");
var contentJSON = JSON.parse(msgJSON.Content);
if(contentJSON.MsgFrom==msgFrom){
item.innerText = "我说: "+contentJSON.Content;
}else{
item.innerText = contentJSON.FromNick+"对你说: "+contentJSON.Content;
}
appendLog(item);
}
}
};
} else {
Expand All @@ -47,6 +120,19 @@
}
};
</script>
<script type="text/javascript">
function getJsonObjLength(jsonObj) {
var Length = 0;
for (var item in jsonObj) {
Length++;
}
return Length;
}
function toAll(){
msgTo = "ALL";
toText.innerText="ALL";
}
</script>
<style type="text/css">
html {
overflow: hidden;
Expand All @@ -61,11 +147,19 @@
}
#log {
background: white;
margin: 0;
padding: 0.5em 0.5em 0.5em 0.5em;
position: absolute;
top: 0.5em;
left: 0.5em;
right: 20em;
bottom: 3em;
overflow: auto;
}
#user {
background: white;
padding: 0.5em 0.5em 0.5em 0.5em;
position: absolute;
top: 0.5em;
right: 0.5em;
bottom: 3em;
overflow: auto;
Expand All @@ -79,13 +173,38 @@
width: 100%;
overflow: hidden;
}
#ulist li{
line-height: 20px;
cursor:pointer;
margin-top: 5px;
}
#ulist2 li{
cursor:pointer;
}
#ulist2 li:hover{
background-color: rgb(169, 180, 71);
}
#ulist li:hover{
background-color: rgb(169, 180, 71);
}

</style>
</head>
<body>
<div id="log"></div>
<div id="user">
<p>用户列表</p>
<ul id="ulist2">
<li onclick="toAll()">全部用户</li>
</ul>
<ul id="ulist">
</ul>
</div>
<form id="form">
<input type="submit" value="Send" />
<input type="submit" value="发送" />
<input type="text" id="msg" size="64"/>
<span>发送对象:</span>
<span id="toText"></span>
</form>
</body>
</html>
Loading

0 comments on commit 0377134

Please sign in to comment.