0
# WebSocket Support
1
2
NettyServer provides automatic WebSocket protocol support for Play Framework applications. When applications define WebSocket endpoints using Play's WebSocket API, NettyServer handles the HTTP upgrade handshake, frame processing, and connection management transparently.
3
4
## Capabilities
5
6
### Automatic WebSocket Integration
7
8
NettyServer automatically detects and handles WebSocket upgrade requests from the standard HTTP request processing pipeline.
9
10
```scala { .api }
11
// NettyServer transparently handles WebSocket requests defined in Play applications
12
// No direct server configuration needed - WebSocket support is built-in
13
14
// WebSocket endpoints are defined using Play's standard WebSocket API
15
import play.api.mvc.WebSocket
16
import play.api.libs.iteratee.{Enumerator, Iteratee}
17
18
def websocketEndpoint = WebSocket.using[String] { request =>
19
val in = Iteratee.foreach[String](println)
20
val out = Enumerator("Hello WebSocket!")
21
(in, out)
22
}
23
```
24
25
### Protocol Support
26
27
NettyServer implements the complete WebSocket protocol specification including:
28
29
- **HTTP Upgrade Handshake**: Automatic negotiation from HTTP to WebSocket protocol
30
- **Frame Processing**: Support for text, binary, close, ping, and pong frames
31
- **Flow Control**: Backpressure handling and connection management
32
- **Error Handling**: Proper connection cleanup and error propagation
33
34
### WebSocket Configuration
35
36
WebSocket behavior can be configured through Netty server configuration.
37
38
```scala { .api }
39
// Configuration keys affecting WebSocket behavior
40
val nettyConfig = Map(
41
"play.server.netty.maxInitialLineLength" -> "4096",
42
"play.server.netty.maxHeaderSize" -> "8192",
43
"play.server.netty.maxChunkSize" -> "8192"
44
)
45
```
46
47
**Usage Examples:**
48
49
```scala
50
import play.api.mvc._
51
import play.api.libs.iteratee._
52
import play.core.server.NettyServer
53
54
// Create server that handles WebSocket endpoints
55
val server = NettyServer.fromRouter() {
56
case GET -> Root / "ws" => WebSocket.using[String] { request =>
57
val in = Iteratee.foreach[String] { message =>
58
println(s"Received: $message")
59
}
60
val out = Enumerator("Welcome!")
61
(in, out)
62
}
63
64
case GET -> Root / "health" => Action { Ok("Server running") }
65
}
66
67
// WebSocket connections are handled automatically by NettyServer
68
// No additional server configuration required
69
```
70
71
### WebSocketable Trait
72
73
The server exposes a trait for checking WebSocket upgrade capability.
74
75
```scala { .api }
76
trait WebSocketable {
77
/** Check if request has proper WebSocket upgrade headers */
78
def check: Boolean
79
80
/** Get specific header value */
81
def getHeader(header: String): String
82
}
83
```
84
85
This trait is used internally by NettyServer to validate WebSocket upgrade requests before performing the handshake.