All Projects → PerfectExamples → Perfect-WebSocketsServer

PerfectExamples / Perfect-WebSocketsServer

Licence: Apache-2.0 license
Perfect Example Module: WebSockets Server

Projects that are alternatives of or similar to Perfect-WebSocketsServer

Perfect-HTTP
Base HTTP Support for Perfect.
Stars: ✭ 29 (-14.71%)
Mutual labels:  perfect, server-side-swift
Perfect-HTTPServer
HTTP server for Perfect.
Stars: ✭ 104 (+205.88%)
Mutual labels:  perfect, server-side-swift
SwiftString
A comprehensive, lightweight string extension for Swift 3.x & 4.0
Stars: ✭ 117 (+244.12%)
Mutual labels:  perfect, server-side-swift
Perfect-SMTP
SMTP Client for Perfect.
Stars: ✭ 19 (-44.12%)
Mutual labels:  perfect, server-side-swift
Perfect-Thread
Core threading library for Perfect Server Side Swift. Includes support for serial and concurrent thread queues, locks, read/write locks and events.
Stars: ✭ 17 (-50%)
Mutual labels:  perfect, server-side-swift
Perfect-Weather
Demonstrate using URL Routes & variables, Fetching of remote data from API's as JSON, reading and transforming to data more appropriately consumable by an API client.
Stars: ✭ 32 (-5.88%)
Mutual labels:  perfect, server-side-swift
Perfect
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)
Stars: ✭ 13,890 (+40752.94%)
Mutual labels:  perfect, server-side-swift
Perfect-Zip
Perfect Zip compression utility.
Stars: ✭ 20 (-41.18%)
Mutual labels:  perfect, server-side-swift
Perfect-JSON-API
An Example JSON API for Perfect
Stars: ✭ 43 (+26.47%)
Mutual labels:  perfect, server-side-swift
Perfect-URL-Shortener
An Example URL Shortener System for Perfect
Stars: ✭ 37 (+8.82%)
Mutual labels:  perfect, server-side-swift
Perfect-URLRouting
Perfect Example Module: URL Routing
Stars: ✭ 20 (-41.18%)
Mutual labels:  perfect, server-side-swift
Perfect-Authentication
OAuth2 Implementations with Facebook, Google, LinkedIn, Slack, SalesForce and GitHub providers.
Stars: ✭ 14 (-58.82%)
Mutual labels:  perfect, server-side-swift
Perfect-XML
XML support for Perfect.
Stars: ✭ 16 (-52.94%)
Mutual labels:  perfect, server-side-swift
SwiftMC
A Minecraft server and proxy written from scratch in Swift.
Stars: ✭ 22 (-35.29%)
Mutual labels:  server-side-swift
Perfect-TensorFlow-Demo-Vision
Perfect TensorFlow Server Example of Computer Vision
Stars: ✭ 39 (+14.71%)
Mutual labels:  perfect
Perfect-Markdown-Editor
This project demonstrates how to build an Online Markdown Editor based on Perfect HTTP Server, Perfect WebSocket and Perfect Markdown.
Stars: ✭ 16 (-52.94%)
Mutual labels:  perfect
Futures
Lightweight promises for iOS, macOS, tvOS, watchOS, and Linux
Stars: ✭ 59 (+73.53%)
Mutual labels:  server-side-swift
PerfectLearnGuide
Are you eager to get programming with Swift and Perfect? This PerfectLearnGuide will help you.
Stars: ✭ 19 (-44.12%)
Mutual labels:  perfect
Swift-FS-China
Swift China Community
Stars: ✭ 44 (+29.41%)
Mutual labels:  perfect
awesome-swift-nio
📖 A collaborative list of all things Swift NIO
Stars: ✭ 81 (+138.24%)
Mutual labels:  server-side-swift

WebSockets Serving

Get Involed with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 3.0 Platforms OS X | Linux License Apache PerfectlySoft Twitter Slack Status

This example illustrates how to set up a WebSocket server and handle a connection.

To use the example with Swift Package Manager, type swift build and then run .build/debug/WebSocketsServer.

To use the example with Xcode, run the WebSockets Server target. This will launch the Perfect HTTP Server.

Navigate in your web browser to http://localhost:8181/

Issues

We are transitioning to using JIRA for all bugs and support related issues, therefore the GitHub issues has been disabled.

If you find a mistake, bug, or any other helpful suggestion you'd like to make on the docs please head over to http://jira.perfect.org:8080/servicedesk/customer/portal/1 and raise it.

A comprehensive list of open issues can be found at http://jira.perfect.org:8080/projects/ISS/issues

Initiating a WebSocket Session

Add one or more URL routes using the Routing.Routes subscript functions. These routes will be the endpoints for the WebSocket session. Set the route handler to WebSocketHandler and provide your custom closure which will return your own session handler.

The following code is taken from the example project and shows how to enable the system and add a WebSocket handler.

func makeRoutes() -> Routes {
	
	var routes = Routes()
    // Add a default route which lets us serve the static index.html file
	routes.add(method: .get, uri: "*", handler: { request, response in
		StaticFileHandler(documentRoot: request.documentRoot).handleRequest(request: request, response: response)
	})
    
    // Add the endpoint for the WebSocket example system
	routes.add(method: .get, uri: "/echo", handler: {
        request, response in
        
        // To add a WebSocket service, set the handler to WebSocketHandler.
        // Provide your closure which will return your service handler.
        WebSocketHandler(handlerProducer: {
            (request: HTTPRequest, protocols: [String]) -> WebSocketSessionHandler? in
            
            // Check to make sure the client is requesting our "echo" service.
            guard protocols.contains("echo") else {
                return nil
            }
            
            // Return our service handler.
            return EchoHandler()
        }).handleRequest(request: request, response: response)
    })
	
	return routes
}

Handling WebSocket Sessions

A WebSocket service handler must impliment the WebSocketSessionHandler protocol. This protocol requires the function handleSession(request: HTTPRequest, socket: WebSocket). This function will be called once the WebSocket connection has been established, at which point it is safe to begin reading and writing messages.

The initial HTTPRequest object which instigated the session is provided for reference. Messages are transmitted through the provided WebSocket object. Call WebSocket.sendStringMessage or WebSocket.sendBinaryMessage to send data to the client. Call WebSocket.readStringMessage or WebSocket.readBinaryMessage to read data from the client. By default, reading will block indefinitely until a message arrives or a network error occurs. A read timeout can be set with WebSocket.readTimeoutSeconds. When the session is over call WebSocket.close().

The example EchoHandler consists of the following.

class EchoHandler: WebSocketSessionHandler {
	
	// The name of the super-protocol we implement.
	// This is optional, but it should match whatever the client-side WebSocket is initialized with.
	let socketProtocol: String? = "echo"
	
	// This function is called by the WebSocketHandler once the connection has been established.
	func handleSession(request: HTTPRequest, socket: WebSocket) {
		
		// Read a message from the client as a String.
		// Alternatively we could call `WebSocket.readBytesMessage` to get binary data from the client.
		socket.readStringMessage {
			// This callback is provided:
			//	the received data
			//	the message's op-code
			//	a boolean indicating if the message is complete (as opposed to fragmented)
			string, op, fin in
			
			// The data parameter might be nil here if either a timeout or a network error, such as the client disconnecting, occurred.
			// By default there is no timeout.
			guard let string = string else {
				// This block will be executed if, for example, the browser window is closed.
				socket.close()
				return
			}
			
			// Print some information to the console for informational purposes.
			print("Read msg: \(string) op: \(op) fin: \(fin)")
			
			// Echo the data we received back to the client.
			// Pass true for final. This will usually be the case, but WebSockets has the concept of fragmented messages.
			// For example, if one were streaming a large file such as a video, one would pass false for final.
			// This indicates to the receiver that there is more data to come in subsequent messages but that all the data is part of the same logical message.
			// In such a scenario one would pass true for final only on the last bit of the video.
			socket.sendStringMessage(string: string, final: true) {
				
				// This callback is called once the message has been sent.
				// Recurse to read and echo new message.
				self.handleSession(request: request, socket: socket)
			}
		}
	}
}

FastCGI Caveat

WebSockets serving is only supported with the stand-alone Perfect HTTP server. At this time, the WebSocket server does not operate with the Perfect FastCGI server.

Further Information

For more information on the Perfect project, please visit perfect.org.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].