Fork me on GitHub
打赏

使用Go语言+Protobuf协议完成一个多人聊天室

软件环境:Goland 

Github地址

一、目的

之前用纯逻辑垒完了一个可登入登出的在线多人聊天室(代码仓库地址),这次学习了Protobuf协议,于是想试着更新下聊天室的版本。

主要目的是为了掌握Protobuf的使用。

 

二、设计思路

通过Protobuf中内置好的编码函数,将要发送的数据进行编码,之后在“编码后的”数据前加入协议号和报头,再转码通过Write与Read函数进行数据的发送和接收。

1,先写好服务端中的监听(Listen)端口函数与客户端上的网络拨号(Dial)函数;

2,客户端,对数据进行解码;

			//客户端,对接收到的数据进行解码
			newTest := &protocol.Conn_ToS{}
			err = proto.Unmarshal(msgdata[0:msgdata_read],newTest)
			if err != nil{
				log.Fatal("unmarshaling error:",err)
			}

			fmt.Println(newTest.GetNickname(),newTest.GetMsg())

  

3,服务端,接收消息;

		//服务端,接收到信息并遍历Map发送消息
                datamsg := make([]byte,255)
		datamsg_read ,err := conn.Read(datamsg)

		if datamsg_read == 0 || err != nil{
			continue
		}
		fmt.Println(datamsg[0:datamsg_read])
		for _,v := range ConnMap{
			v.Write(datamsg[0:datamsg_read])
		}    

 

三、注意点

1,注意字节处的拼接,建议使用append函数

2,处理连接处注意对数据编码解码的处理

3,设置Map存所有连服务端的客户端连接,并到需要时遍历输出和转发消息至Map中所有的连接;

 

四、效果

Server端

 

Client1端

 

 

Client2端

 

 

Client3端

 

 

posted @ 2018-08-28 21:39  Zoctopus_Zhang  阅读(1426)  评论(1编辑  收藏  举报
// function btn_donateClick() { var DivPopup = document.getElementById('Div_popup'); var DivMasklayer = document.getElementById('div_masklayer'); DivMasklayer.style.display = 'block'; DivPopup.style.display = 'block'; var h = Div_popup.clientHeight; with (Div_popup.style) { marginTop = -h / 2 + 'px'; } } function MasklayerClick() { var masklayer = document.getElementById('div_masklayer'); var divImg = document.getElementById("Div_popup"); masklayer.style.display = "none"; divImg.style.display = "none"; } setTimeout( function () { document.getElementById('div_masklayer').onclick = MasklayerClick; document.getElementById('btn_donate').onclick = btn_donateClick; var a_gzw = document.getElementById("guanzhuwo"); a_gzw.href = "javascript:void(0);"; $("#guanzhuwo").attr("onclick","follow('33513f9f-ba13-e011-ac81-842b2b196315');"); }, 900);