シャオハオシオン

惟有爱情、美食、还有代码不可辜负

websocket 初尝试之 echo demo

最近需要做一个消息通知的推送,开始在实践 websocket

server port:9091

package main  
import (  
 "fmt"  
 "log"
 "net/http"
 "github.com/gorilla/websocket"
)  
  
var upgrader = websocket.Upgrader{  
 CheckOrigin: func(r *http.Request) bool {  
  return true  
  },  
} // use default options  
  
func Echo(w http.ResponseWriter, r *http.Request) {  
 c, err := upgrader.Upgrade(w, r, nil)  
  if err != nil {  
  log.Print("upgrade:", err)  
  return  
  }  
  defer c.Close()  
  for {  
 mt, message, err := c.ReadMessage()  
  if err != nil {  
  log.Println("read:", err)  
  break  
  }  
  log.Printf("recv: %s", message)  
 err = c.WriteMessage(mt, message)  
  if err != nil {  
  log.Println("write:", err)  
  break  
  }  
 }}  
func main() {  
  http.HandleFunc("/echo", Echo)  
  fmt.Println("start server  port:9091")  
  if err := http.ListenAndServe(":9091", nil); err != nil {  
  log.Fatal("ListenAndServe:1234:", err)  
 }}

client:

<!DOCTYPE html>

<html>

<head>
	<title>websocket</title>
</head>
<body>
	<h1>Echo Test</h1>
	<input type="text" id="sendTxt">
	<button id="sendBtn">发送</button>
	<div id="recv"></div>


	<script type="text/javascript">
		let ws = new WebSocket("ws://127.0.0.1:9091/echo")
		ws.onopen = function () {
			// body...
			console.log("websocket open");
			document.getElementById('recv').innerHTML = 'Connected';
		}
		ws.oncolse = function (e) {
			// body...
			console.log("consoled");
		}

		ws.onmessage=function (e) {
			// body...
			console.log(e.data)
			document.getElementById('recv').innerHTML = e.data;
		}
		document.getElementById('sendBtn').onclick=function(){
			var txt=document.getElementById('sendTxt').value;
			console.log(txt)
			ws.send(txt)
		}

	</script>
</body>
</html>

读书使人充实,思考使人深邃,交谈使人清醒。 - 这是一条小尾巴~

留下你的脚步