码迷,mamicode.com
首页 > 其他好文 > 详细

在golang中使用socket.io

时间:2020-03-14 13:19:49      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:nand   ola   append   hand   listen   mamicode   sse   sage   return   

客户端试过了socket.js,感觉不先进。

再试试正宗的socket.io吧。

后端用golang改造。

main.go

package main

import (
	"fmt"
	"log"
	"net/http"

	socketio "github.com/googollee/go-socket.io"
)

func main() {
	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}

	//===========/chat1===========
	server.OnEvent("/", "default notice", func(s socketio.Conn, msg string) {
		fmt.Println("default notice:", msg)
		s.Emit("default reply", "default notice reply: "+msg)
	})

	//===========/chat1===========
	server.OnEvent("/chat1", "chat1 notice", func(s socketio.Conn, msg string) {
		fmt.Println("chat1 notice:", msg)
		s.Emit("chat1 reply", "chat1 notice reply: "+msg)
	})

	//===========/chat2===========

	server.OnEvent("/chat2", "chat2 msg", func(s socketio.Conn, msg string) string {
		s.SetContext(msg)
		return "chat2 msg recv " + msg
	})

	go server.Serve()
	defer server.Close()

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("./asset")))
	log.Println("Serving at localhost:8000...")
	log.Fatal(http.ListenAndServe(":8000", nil))
}

  

index.html

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket1 = io("/chat1");
      var socket2 = io("/chat2");
      socket1.on(‘chat1 reply‘, function(msg){
        $(‘#messages‘).append($(‘<li>‘).text(msg));
      });
      $(‘form‘).submit(function(){
        socket2.emit(‘chat2 msg‘, $(‘#m‘).val(), function(data){
		  console.log(data);
          $(‘#messages‘).append($(‘<li>‘).text(‘ACK CALLBACK: ‘ + data));
        });
        socket1.emit(‘chat1 notice‘, $(‘#m‘).val());
        $(‘#m‘).val(‘‘);
        return false;
      });
    </script>
  </body>
</html>

  技术图片

在golang中使用socket.io

标签:nand   ola   append   hand   listen   mamicode   sse   sage   return   

原文地址:https://www.cnblogs.com/aguncn/p/12491239.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!