2015-10-02 03:24:38 +02:00
|
|
|
---
|
|
|
|
title: WebSocket
|
|
|
|
menu:
|
|
|
|
main:
|
|
|
|
parent: recipes
|
|
|
|
---
|
2015-06-30 20:51:08 +02:00
|
|
|
|
2015-07-03 08:21:21 +02:00
|
|
|
## Server
|
|
|
|
|
2015-06-30 20:51:08 +02:00
|
|
|
`server.go`
|
|
|
|
|
|
|
|
```go
|
2015-06-10 00:24:01 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2015-07-13 00:41:46 +02:00
|
|
|
"fmt"
|
|
|
|
|
2015-06-10 05:06:51 +02:00
|
|
|
"github.com/labstack/echo"
|
2015-06-10 00:24:01 +02:00
|
|
|
mw "github.com/labstack/echo/middleware"
|
2015-07-03 07:55:00 +02:00
|
|
|
"golang.org/x/net/websocket"
|
2015-06-10 00:24:01 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
e := echo.New()
|
2015-07-03 07:55:00 +02:00
|
|
|
|
2015-06-10 00:24:01 +02:00
|
|
|
e.Use(mw.Logger())
|
2015-07-03 07:55:00 +02:00
|
|
|
e.Use(mw.Recover())
|
|
|
|
|
|
|
|
e.Static("/", "public")
|
|
|
|
e.WebSocket("/ws", func(c *echo.Context) (err error) {
|
|
|
|
ws := c.Socket()
|
|
|
|
msg := ""
|
|
|
|
|
|
|
|
for {
|
|
|
|
if err = websocket.Message.Send(ws, "Hello, Client!"); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if err = websocket.Message.Receive(ws, &msg); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-07-13 00:41:46 +02:00
|
|
|
fmt.Println(msg)
|
2015-07-03 07:55:00 +02:00
|
|
|
}
|
|
|
|
return
|
2015-06-10 00:24:01 +02:00
|
|
|
})
|
2015-07-03 07:55:00 +02:00
|
|
|
|
2015-06-10 00:24:01 +02:00
|
|
|
e.Run(":1323")
|
|
|
|
}
|
2015-06-30 20:51:08 +02:00
|
|
|
```
|
|
|
|
|
2015-07-03 08:21:21 +02:00
|
|
|
## Client
|
|
|
|
|
2015-07-03 07:55:00 +02:00
|
|
|
`index.html`
|
|
|
|
|
|
|
|
```html
|
|
|
|
<!doctype html>
|
|
|
|
<html lang="en">
|
|
|
|
<head>
|
|
|
|
<meta charset="utf-8">
|
|
|
|
<title>WebSocket</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<p id="output"></p>
|
|
|
|
|
|
|
|
<script>
|
|
|
|
var loc = window.location;
|
|
|
|
var uri = 'ws:';
|
|
|
|
|
|
|
|
if (loc.protocol === 'https:') {
|
|
|
|
uri = 'wss:';
|
|
|
|
}
|
|
|
|
uri += '//' + loc.host;
|
|
|
|
uri += loc.pathname + 'ws';
|
|
|
|
|
|
|
|
ws = new WebSocket(uri)
|
|
|
|
|
|
|
|
ws.onopen = function() {
|
|
|
|
console.log('Connected')
|
|
|
|
}
|
|
|
|
|
|
|
|
ws.onmessage = function(evt) {
|
|
|
|
var out = document.getElementById('output');
|
|
|
|
out.innerHTML += evt.data + '<br>';
|
|
|
|
}
|
|
|
|
|
|
|
|
setInterval(function() {
|
|
|
|
ws.send('Hello, Server!');
|
|
|
|
}, 1000);
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
</html>
|
|
|
|
```
|
|
|
|
|
2015-07-03 08:21:21 +02:00
|
|
|
## Output
|
|
|
|
|
|
|
|
`Client`
|
|
|
|
|
|
|
|
```sh
|
|
|
|
Hello, Client!
|
|
|
|
Hello, Client!
|
|
|
|
Hello, Client!
|
|
|
|
Hello, Client!
|
|
|
|
Hello, Client!
|
|
|
|
```
|
|
|
|
|
|
|
|
`Server`
|
|
|
|
|
|
|
|
```sh
|
|
|
|
Hello, Server!
|
|
|
|
Hello, Server!
|
|
|
|
Hello, Server!
|
|
|
|
Hello, Server!
|
|
|
|
Hello, Server!
|
|
|
|
```
|
|
|
|
|
2015-06-30 21:10:35 +02:00
|
|
|
## [Source Code](https://github.com/labstack/echo/blob/master/recipes/websocket)
|