A new client connected to the server. We haven't accepted the connection yet, though.
Modulewebsockets-0.13.0.0Haskell2010
Network.WebSockets
- 22 types
- 1 class
- 39 values
- Packagewebsockets-0.13.0.0
- Exports62
- LanguageHaskell2010
- LicenceBSD-3-Clause
- SourceConnection.hs
Incoming connections and handshaking
10 declarationsUseful for e.g. inspecting the request path.
Accept a pending connection, turning it into a Connection.
This datatype allows you to set options for acceptRequestWith. It is strongly recommended to use defaultAcceptRequest and then modify the various fields, that way new fields introduced in the library do not break your code.
Constructors
AcceptRequestacceptSubprotocol :: !Maybe ByteStringThe subprotocol to speak with the client. If
pendingSubprotcolsis non-empty, acceptSubprotocol must be one of the subprotocols from the list.acceptHeaders :: !HeadersExtra headers to send with the response.
This function is like acceptRequest but allows you to set custom options using the AcceptRequest datatype.
rejectRequest :: PendingConnectionConnection to reject
-> ByteStringRejection response body
-> IO ()
Requires calling pendingStream and close.
Parameters that allow you to tweak how a request is rejected. Please use defaultRejectRequest and modify fields using record syntax so your code will not break when new fields are added.
Constructors
RejectRequestrejectCode :: !IntThe status code, 400 by default.
rejectMessage :: !ByteStringThe message, "Bad Request" by default
rejectHeaders :: HeadersExtra headers to be sent with the response.
rejectBody :: !ByteStringReponse body of the rejection.
rejectRequestWith :: PendingConnectionConnection to reject
-> RejectRequestParams on how to reject the request
-> IO ()
Main connection type
1 declarationOptions for connections
2 declarationsSet options for a Connection. Please do not use this constructor
directly, but rather use defaultConnectionOptions and then set the fields
you want, e.g.:
myOptions = defaultConnectionOptions {connectionStrictUnicode = True}This way your code does not break if the library introduces new fields.
Constructors
ConnectionOptionsconnectionOnPong :: !IO ()Whenever a
pongis received, this IO action is executed. It can be used to tickle connections or fire missiles.connectionTimeout :: !IntTimeout for connection establishment in seconds. Only used in the client.
connectionCompressionOptions :: !CompressionOptionsEnable PermessageDeflate.
connectionStrictUnicode :: !BoolEnable strict unicode on the connection. This means that if a client (or server) sends invalid UTF-8, we will throw a
UnicodeExceptionrather than replacing it by the unicode replacement character U+FFFD.connectionFramePayloadSizeLimit :: !SizeLimitThe maximum size for incoming frame payload size in bytes. If a frame exceeds this limit, a
ParseExceptionis thrown.connectionMessageDataSizeLimit :: !SizeLimitconnectionFrameSizeLimitis often not enough since a malicious client can send many small frames to create a huge message. This limit allows you to protect from that. If a message exceeds this limit, aParseExceptionis thrown.Note that, if compression is enabled, we check the size of the compressed messages, as well as the size of the uncompressed messages as we are deflating them to ensure we don't use too much memory in any case.
The default connection options:
Nothing happens when a pong is received.
Compression is disabled.
Lenient unicode decoding.
30 second timeout for connection establishment.
Compression options
Instances2Eq, Show
Eq CompressionOptionsDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.OptionsShow CompressionOptionsDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.Options
Four extension parameters are defined for "permessage-deflate" to help endpoints manage per-connection resource usage.
"server_no_context_takeover"
"client_no_context_takeover"
"server_max_window_bits"
"client_max_window_bits"
Instances2Eq, Show
Eq PermessageDeflateDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.OptionsShow PermessageDeflateDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.Options
Protection limits
A size limit, in bytes. The Monoid instance takes the minimum limit.
Constructors
Instances4Eq, Show, Semigroup, Monoid
Eq SizeLimitDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.OptionsShow SizeLimitDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.OptionsSemigroup SizeLimitDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.OptionsMonoid SizeLimitDefined in websockets-0.13.0.0 · Network.WebSockets.Connection.Options
Sending and receiving messages
13 declarationsReceive an application message. Automatically respond to control messages.
When the peer sends a close control message, an exception of type CloseRequest is thrown. The peer can send a close control message either to initiate a close or in response to a close message we have sent to the peer. In either case the CloseRequest exception will be thrown. The RFC specifies that the server is responsible for closing the TCP connection, which should happen after receiving the CloseRequest exception from this function.
This will throw ConnectionClosed if the TCP connection dies unexpectedly.
Receive a message, converting it to whatever format is needed.
Send a DataMessage. This allows you send both human-readable text and binary data. This is a slightly more low-level interface than sendTextData or sendBinaryData.
Send a collection of DataMessages. This is more efficient than calling sendDataMessage many times.
Send a textual message. The message will be encoded as UTF-8. This should be the default choice for human-readable text-based protocols such as JSON.
Send a number of textual messages. This is more efficient than calling sendTextData many times.
Send a binary message. This is useful for sending binary blobs, e.g. images, data encoded with MessagePack, images...
Send a number of binary messages. This is more efficient than calling sendBinaryData many times.
Send a friendly close message. Note that after sending this message, you should still continue calling receiveDataMessage to process any in-flight messages. The peer will eventually respond with a close control message of its own which will cause receiveDataMessage to throw the CloseRequest exception. This exception is when you can finally consider the connection closed.
Send a friendly close message and close code. Similar to sendClose, you should continue calling receiveDataMessage until you receive a CloseRequest exception.
See http://tools.ietf.org/html/rfc6455#section-7.4 for a list of close codes.
Send a ping
HTTP Types
6 declarationsRequest headers
A request with a body
Constructors
An HTTP request. The request body is not yet read.
Constructors
Instances1Show
Show RequestHeadDefined in websockets-0.13.0.0 · Network.WebSockets.Http
List of subprotocols specified by the client, in order of preference. If the client did not specify a list of subprotocols, this will be the empty list.
A response including a body
Constructors
HTTP response, without body.
Constructors
Instances1Show
Show ResponseHeadDefined in websockets-0.13.0.0 · Network.WebSockets.Http
WebSocket message types
4 declarationsThe kind of message a server application typically deals with
Constructors
ControlMessage ControlMessageDataMessage Bool Bool Bool DataMessageReserved bits, actual message
Different control messages
Constructors
Instances2Eq, Show
Eq ControlMessageDefined in websockets-0.13.0.0 · Network.WebSockets.TypesShow ControlMessageDefined in websockets-0.13.0.0 · Network.WebSockets.Types
For an end-user of this library, dealing with Frames would be a bit
low-level. This is why define another type on top of it, which represents
data for the application layer.
There are currently two kinds of data messages supported by the WebSockets protocol:
Textual UTF-8 encoded data. This corresponds roughly to sending a String in JavaScript.
Binary data. This corresponds roughly to send an ArrayBuffer in JavaScript.
Constructors
Text ByteString (Maybe Text)A textual message. The second field might contain the decoded UTF-8 text for caching reasons. This field is computed lazily so if it's not accessed, it should have no performance impact.
Binary ByteStringA binary message.
Instances2Eq, Show
Eq DataMessageDefined in websockets-0.13.0.0 · Network.WebSockets.TypesShow DataMessageDefined in websockets-0.13.0.0 · Network.WebSockets.Types
In order to have an even more high-level API, we define a typeclass for values the user can receive from and send to the socket. A few warnings apply:
Natively, everything is represented as a ByteString, so this is the fastest instance
You should only use the Text or the Text instance when you are sure that the data is UTF-8 encoded (which is the case for Text messages).
Messages can be very large. If this is the case, it might be inefficient to use the strict ByteString and Text instances.
Methods
fromDataMessage :: DataMessage -> afromLazyByteString :: ByteString -> atoLazyByteString :: a -> ByteString
Instances4WebSocketsData
WebSocketsData ByteStringDefined in websockets-0.13.0.0 · Network.WebSockets.TypesWebSocketsData ByteStringDefined in websockets-0.13.0.0 · Network.WebSockets.TypesWebSocketsData TextDefined in websockets-0.13.0.0 · Network.WebSockets.TypesWebSocketsData TextDefined in websockets-0.13.0.0 · Network.WebSockets.Types
Exceptions
2 declarationsError in case of failed handshake. Will be thrown as an Exception.
TODO: This should probably be in the Handshake module, and is solely here to prevent a cyclic dependency.
Constructors
NotSupportedWe don't have a match for the protocol requested by the client. todo: version parameter
MalformedRequest RequestHead StringThe request was somehow invalid (missing headers or wrong security token)
MalformedResponse ResponseHead StringThe servers response was somehow invalid (missing headers or wrong security token)
RequestRejected RequestHead ResponseHeadThe request was well-formed, but the library user rejected it. (e.g. "unknown path")
ConnectionTimeoutThe connection timed out
OtherHandshakeException Stringfor example "EOF came too early" (which is actually a parse error) or for your own errors. (like "unknown path"?)
Instances2Show, Exception
Show HandshakeExceptionDefined in websockets-0.13.0.0 · Network.WebSockets.HttpException HandshakeExceptionDefined in websockets-0.13.0.0 · Network.WebSockets.Http
Various exceptions that can occur while receiving or transmitting messages
Constructors
CloseRequest Word16 ByteStringThe peer has requested that the connection be closed, and included a close code and a reason for closing. When receiving this exception, no more messages can be sent. Also, the server is responsible for closing the TCP connection once this exception is received.
See http://tools.ietf.org/html/rfc6455#section-7.4 for a list of close codes.
ConnectionClosedThe peer unexpectedly closed the connection while we were trying to receive some data. This is a violation of the websocket RFC since the TCP connection should only be closed after sending and receiving close control messages.
ParseException StringThe client sent garbage, i.e. we could not parse the WebSockets stream.
UnicodeException StringThe client sent invalid UTF-8. Note that this exception will only be thrown if strict decoding is set in the connection options.
Instances3Eq, Show, Exception
Eq ConnectionExceptionDefined in websockets-0.13.0.0 · Network.WebSockets.TypesShow ConnectionExceptionDefined in websockets-0.13.0.0 · Network.WebSockets.TypesException ConnectionExceptionDefined in websockets-0.13.0.0 · Network.WebSockets.Types
Running a standalone server
6 declarationsWebSockets application that can be ran by a server. Once this IO action finishes, the underlying socket is closed automatically.
runServer Provides a simple server. This function blocks forever. Note that this is merely provided for quick-and-dirty or internal applications, but for real applications, you should use a real server.
For example:
Performance is reasonable under load, but:
No protection against DoS attacks is provided.
No logging is performed.
...
Glue for using this package with real servers is provided by:
Deprecated. Use runServerWithOptions instead
A version of runServer which allows you to customize some options.
Constructors
Customizable version of runServer. Never returns until killed.
Please use the defaultServerOptions combined with record updates to set the fields you want. This way your code is unlikely to break on future changes.
Utilities for writing your own server
3 declarationsCreate a standardized socket on which you can listen for incomming
connections. Should only be used for a quick and dirty solution! Should be
preceded by the call Network.Socket.withSocketsDo.
Turns a socket, connected to some client, into a PendingConnection. The PendingConnection should be closed using pendingStream and close later.
More general version of makePendingConnection for Stream instead of a Socket.
Running a client
6 declarationsA client application interacting with a single server. Once this IO action finished, the underlying socket is closed automatically.
runClientWith runClientWithSocket runClientWithStream newClientConnection :: StreamStream that will be used by the new Connection.
-> StringHost
-> StringPath
-> ConnectionOptionsConnection options
-> HeadersCustom headers to send
-> IO Connection
Build a new Connection from the client's point of view.
WARNING: Be sure to call close on the given Stream after you are done using the Connection in order to properly close the communication channel. runClientWithStream handles this for you, prefer to use it when possible.
Utilities
5 declarationsOptions for ping-pong
Make sure that the ping interval is less than the pong timeout, for example N/2.
Constructors
PingPongOptionspingInterval :: IntInterval in seconds
pongTimeout :: IntTimeout in seconds
pingAction :: IO ()Action to perform after sending a ping
Default options for ping-pong
Ping every 15 seconds, timeout after 30 seconds
Run an application with ping-pong enabled. Raises PongTimeout if a pong is not received.
Can used with Client and Server connections.
withPingThread :: Connection-> IntSecond interval in which pings should be sent.
-> IO ()Repeat this after sending a ping.
-> IO aApplication to wrap with a ping thread.
-> IO aExecutes application and kills ping thread when done.
Forks a ping thread, sending a ping message every n seconds over the
connection. The thread is killed when the inner IO action is finished.
This is useful to keep idle connections open through proxies and whatnot. Many (but not all) proxies have a 60 second default timeout, so based on that sending a ping every 30 seconds is a good idea.
Note that usually you want to use withPingPong to timeout the connection if a pong is not received.
Deprecated. Use withPingThread instead
DEPRECATED: Use withPingThread instead.
Forks a ping thread, sending a ping message every n seconds over the
connection. The thread dies silently if the connection crashes or is closed.
This is useful to keep idle connections open through proxies and whatnot. Many (but not all) proxies have a 60 second default timeout, so based on that sending a ping every 30 seconds is a good idea.