Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

WebSocket Integration in Scala

Introduction

WebSockets provide a way to open a persistent connection between a client and a server, allowing for real-time communication. In this tutorial, we will explore how to integrate WebSocket functionality into a Scala application. We will use the Akka framework, which simplifies the process of building concurrent and distributed applications.

Prerequisites

To follow this tutorial, you should have a basic understanding of Scala and some familiarity with the Akka framework. Additionally, ensure that you have the following installed:

  • Java Development Kit (JDK) 8 or higher
  • SBT (Scala Build Tool)

Setting Up the Project

Start by creating a new SBT project. Create a directory for your project and navigate into it:

mkdir websocket-example
cd websocket-example
sbt new scala/scala-seed.g8

This command will create a new Scala project template. Now, navigate to the `build.sbt` file and add the following dependencies for Akka:

libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.6.18"
libraryDependencies += "com.typesafe.akka" %% "akka-stream" % "2.6.18"
libraryDependencies += "com.typesafe.akka" %% "akka-http" % "10.2.9"

Save the file, and your project is now set up to use Akka.

Creating a WebSocket Server

Next, we will create a simple WebSocket server. Create a new file called `WebSocketServer.scala` in the `src/main/scala` directory and add the following code:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

object WebSocketServer {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem("websocket-system")
implicit val materializer = ActorMaterializer()
val route = path("ws") {
handleWebSocketMessages(socketFlow)
}
Http().bindAndHandle(route, "localhost", 8080)
}
def socketFlow: Flow[Message, Message, Any] = {
Flow[Message].collect {
case TextMessage.Strict(txt) => TextMessage(s"Echo: $txt")
}
}
}

This code sets up a WebSocket server that listens for connections on `localhost:8080`. When a client sends a text message, the server echoes it back.

Running the WebSocket Server

To run the server, execute the following command in your project directory:

sbt run

Your server should now be running. You can test the WebSocket server using a client implementation.

Creating a WebSocket Client

For testing, we can create a simple HTML client. Create a new file named `index.html` in the project root directory:

<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<script>
const socket = new WebSocket("ws://localhost:8080/ws");
socket.onmessage = function(event) {
console.log(event.data);
};
socket.onopen = function() {
socket.send("Hello, Server!");
};
</script>
</html>

This HTML file creates a WebSocket client that connects to the server you created. When the connection is open, it sends a message to the server and logs any messages received from the server.

Testing the WebSocket Client

Open the `index.html` file in your web browser. You should see the message "Echo: Hello, Server!" logged in your browser's console. This confirms that the client-server communication is working as expected.

Conclusion

In this tutorial, you learned how to integrate WebSocket functionality into a Scala application using the Akka framework. You created a simple WebSocket server that echoes messages and a client that connects to it. WebSockets are a powerful tool for building real-time applications, and Akka makes it easy to implement them in Scala.