常见传输协议 不够全面会陆续补充
协议 | 链接 | 面向 | 默认端口 | 备注 |
HTTP | TCP链接 | 网页 | 80 | 超文本传输协议 |
FTP | TCP链接 | 文件 | 21 | 文件传输协议 |
WebSockets | TCP链接(单个链接全双工通信) | 数据 | 80 | html5 客户端和服务端全双工通信 |
wss | 443 |
WebSockets 应用
server 端代码,语言go
package wsApi import ( "fmt" "net/http" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) var upGrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } func Ping(c *gin.Context) { fmt.Println(123333); ws, err := upGrader.Upgrade(c.Writer, c.Request, nil) if err != nil { return } defer ws.close() for { //读取ws中的数据 mt, message, err := ws.ReadMessage() if err != nil { break } //如果发送的信息是ping则返回pong if string(message) == "ping" { message = []byte("pong") } //写入ws数据 向前端返回数据 err = ws.WriteMessage(mt, message) if err != nil { break } } }
client 端代码
startWS(){ if(window.WebSocket){ let socket = new WebSocket('ws://localhost:8081/wsapi'); socket.onopen = () => { socket.send('hhahahahah') } socket.onmessage = (evt) => { var received_msg = evt.data; console.log("数据已接收...", received_msg); } socket.onclose = function(){ // 关闭 websocket console.log("连接已关闭..."); }; } },