<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lutescu Dan on Medium]]></title>
        <description><![CDATA[Stories by Lutescu Dan on Medium]]></description>
        <link>https://medium.com/@ldanadrian?source=rss-3584379beeda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*8ZPkxOCMw4ovHUlqFNiHkA.jpeg</url>
            <title>Stories by Lutescu Dan on Medium</title>
            <link>https://medium.com/@ldanadrian?source=rss-3584379beeda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:21:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ldanadrian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating Interactive Multiplayer Games with Flutter]]></title>
            <link>https://medium.com/@ldanadrian/creating-interactive-multiplayer-games-with-flutter-21103e3d90bf?source=rss-3584379beeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/21103e3d90bf</guid>
            <category><![CDATA[multiplayer-functionality]]></category>
            <category><![CDATA[user-input-handling]]></category>
            <category><![CDATA[game-logic-design]]></category>
            <category><![CDATA[interactive-ui]]></category>
            <category><![CDATA[flutter-game-development]]></category>
            <dc:creator><![CDATA[Lutescu Dan]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 11:16:21 GMT</pubDate>
            <atom:updated>2023-07-20T11:33:47.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*_kLSYXvvc9C7yAxTcw8OaA.jpeg" /></figure><h4>Introduction</h4><p>With the booming popularity of the gaming industry, there is an increasing demand for developers who can create interactive and visually appealing games. Flutter, a cross-platform framework developed by Google, offers a powerful solution for game development. In this article, we will explore the world of game development with Flutter and learn how to create engaging and immersive gaming experiences.</p><p>To get started with Flutter game development, we first need to set up our development environment. This involves installing Flutter SDK, setting up an IDE (Integrated Development Environment) such as Android Studio or Visual Studio Code, and configuring the necessary plugins. Once the development environment is ready, we can dive into the basics of game development with Flutter.</p><p>Designing game logic is a crucial aspect of game development. We need to define the mechanics and rules of our game, such as player movements, interactions, scoring system, and win/loss conditions. We will leverage the object-oriented programming principles of Flutter to create modular and reusable code that handles the game logic effectively.</p><p>Building an interactive and visually appealing user interface (UI) is essential for any game. Flutter provides a wide range of widgets that can be used to create stunning UI elements such as buttons, animations, images, and more. We will explore these widgets and learn how to design the UI for our game, ensuring a seamless and immersive gameplay experience for the users.</p><h4>Getting Started with Flutter Game Development</h4><p>To kickstart our Flutter game development journey, we need to set up our development environment. This involves installing the Flutter SDK and configuring it with our preferred IDE, whether it’s Android Studio or Visual Studio Code. The Flutter SDK comes with a command-line tool called flutter which provides various commands to create, build, and run Flutter projects.</p><p>Once we have our development environment set up, we can start by understanding the basics of game development with Flutter. Flutter follows a reactive programming model, where the UI is rebuilt whenever there is a change in the underlying data. We will explore the concept of widgets, which are the building blocks of Flutter UI, and how they can be used to create interactive elements in our game.</p><p>In Flutter game development, it is important to handle user input effectively. Whether it’s touch events, gestures, or keyboard inputs, we need to capture and process them to drive the gameplay. We will learn how to utilize Flutter’s event handling mechanisms to detect and respond to user input, enabling smooth and responsive game interactions.</p><p>Furthermore, we will delve into the concept of game loops, which are responsible for updating and rendering the game state at regular intervals. Game loops play a crucial role in maintaining the game’s responsiveness and smooth gameplay experience. We will explore how to implement game loops using Flutter’s animation framework and ensure our game runs seamlessly even on different devices and screen sizes.</p><h4>Designing Game Logic</h4><p>Designing the game logic is a critical step in Flutter game development. It involves defining the rules, mechanics, and behavior of our game. By leveraging the object-oriented programming principles of Flutter, we can create modular and reusable code that handles the game logic effectively.</p><p>One important aspect of game logic design is managing the game state. This includes keeping track of variables such as scores, levels, and player lives. We can create dedicated classes and data structures to encapsulate the game state and provide methods for updating and retrieving relevant information.</p><p>In addition to managing the game state, we need to handle game events and interactions. This includes detecting collisions between game elements, handling user input, and triggering game events based on specific conditions. By implementing event listeners and callbacks, we can respond to these events and update the game state accordingly.</p><p>Implementing game mechanics requires a deep understanding of algorithms and data structures. Whether it’s pathfinding, physics simulation, or artificial intelligence, we need to choose the right algorithms and data structures to ensure efficient and realistic gameplay. Flutter provides various libraries and packages that can be integrated into our game to handle complex game mechanics.</p><h4>Building Interactive Game UI</h4><p>Creating an interactive and visually appealing user interface (UI) is crucial for a successful game. In Flutter, we have access to a wide range of widgets that can be used to design stunning UI elements such as buttons, animations, images, and more. These widgets can be customized and styled to match the aesthetics of our game.</p><p>One important aspect of building the game UI is handling animations and transitions. Flutter provides an animation framework that allows us to create smooth and fluid animations for our game. We can define animations for various game elements, such as character movements, object transitions, and UI effects.</p><p>To enhance the user experience, we can also incorporate audio and sound effects into our game. Flutter provides audio playback capabilities that can be used to add background music, sound effects, and voiceovers to our game. We can synchronize the audio with specific game events to create an immersive gameplay experience.</p><p>Another aspect to consider when building the game UI is responsiveness. Flutter provides flexible layout widgets, such as Row and Column, that automatically adjust the UI elements based on the screen size and orientation. This ensures that our game UI looks great on different devices and screen resolutions.</p><h4>Multiplayer Functionality with Flutter</h4><p>Adding multiplayer functionality to a game can greatly enhance the gaming experience and allow players to compete or collaborate with each other. In Flutter, we can implement real-time multiplayer functionality using various approaches and technologies.</p><p>One common approach is to use a client-server architecture, where players connect to a central server to exchange data and interact with each other. We can utilize sockets or HTTP protocols to establish communication between the game clients and the server. By implementing server-side logic and handling client-server synchronization, we can enable seamless multiplayer gameplay.</p><p>Another approach is to leverage third-party services and platforms that provide ready-made multiplayer solutions. For example, Firebase Realtime Database or Google Play Games Services offer multiplayer functionalities that can be easily integrated into our Flutter game. These services handle the complexities of real-time data synchronization and provide matchmaking capabilities.</p><p>Implementing multiplayer functionality requires careful consideration of game networking and data synchronization. We need to manage game state updates, handle network latency and disconnections, and ensure fair gameplay among all players. By utilizing Flutter’s networking capabilities and integrating multiplayer libraries or services, we can create engaging and competitive multiplayer games.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21103e3d90bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Data Structures in Python]]></title>
            <link>https://medium.com/@ldanadrian/mastering-data-structures-in-python-5f463369c648?source=rss-3584379beeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f463369c648</guid>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linked-list-operations]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Lutescu Dan]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 09:19:03 GMT</pubDate>
            <atom:updated>2023-07-20T09:19:03.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wqFfQUeiCkY-eZL4WuCrg.jpeg" /></figure><h3>1. Introduction to Data Structures</h3><p>Data structures are an essential part of any programming language. They provide a systematic way of organizing and storing data so that it can be easily accessed and manipulated. Understanding data structures is crucial for efficient coding and problem-solving.</p><p>In this chapter, we will explore the fundamental concepts of data structures in Python. We will start by discussing the importance of data structures and their role in computer science. We will then dive into various types of data structures and understand their characteristics and use cases.</p><p>To illustrate these concepts, let’s consider an example. Imagine you are building a social media application where users can post updates, add friends, and like posts. To effectively manage all this data, you will need data structures like arrays, lists, and dictionaries. Each data structure will serve a specific purpose, such as storing user information, tracking user connections, or organizing posts by popularity.</p><p>By the end of this chapter, you will have a solid foundation in data structures, enabling you to choose the right structure for your programming needs. Additionally, we will go beyond built-in data structures and explore how to implement custom data structures in Python, allowing you to tailor them to your specific requirements.</p><p>Now, let’s dive into the world of data structures and unleash their power in Python!</p><h3><strong>2. Arrays and Lists: Building Blocks of Data Structures</strong></h3><p>Arrays and lists are fundamental data structures in Python that allow for the storage and manipulation of data. An array is a collection of elements of the same type, stored in contiguous memory locations. This makes accessing elements by their index very efficient. In Python, arrays are implemented using the built-in array module.</p><p>Lists, on the other hand, are more flexible and can store elements of different types. They are implemented as dynamic arrays, which means their size can change during runtime. Lists provide additional methods for adding, removing, and modifying elements, making them a versatile data structure in Python.</p><p>Here’s an example of how arrays and lists can be used in Python:</p><pre># Creating an array<br>import array as arr<br>my_array = arr.array(&#39;i&#39;, [1, 2, 3, 4, 5])<br><br># Accessing elements in an array<br>print(my_array[0])  # Output: 1<br><br># Creating a list<br>my_list = [1, 2, 3, &quot;four&quot;, &quot;five&quot;]<br><br># Adding elements to a list<br>my_list.append(6)<br>my_list.insert(3, &quot;three&quot;)<br><br># Modifying elements in a list<br>my_list[4] = 5<br><br># Removing elements from a list<br>my_list.remove(&quot;four&quot;)<br>del my_list[0]<br><br># Accessing elements in a list<br>print(my_list[2])  # Output: 3</pre><p>Understanding how arrays and lists work is crucial for building more complex data structures, as they serve as the building blocks for many algorithms and data manipulation tasks.</p><h3>3. Stacks and Queues: Managing Data in a LIFO and FIFO Manner</h3><p>Stacks and queues are essential data structures that help manage and manipulate data in a specific manner.</p><p>In a stack, also known as a Last-In-First-Out (LIFO) data structure, elements are added and removed from one end, known as the top of the stack. When a new element is added, it becomes the top element, and when an element is removed, the element beneath it becomes the new top. Think of a stack of books — when a new book is added, it goes on top, and when a book is removed, the book beneath it becomes accessible. This makes stacks ideal for tasks like checking for balanced parentheses or evaluating arithmetic expressions.</p><p>On the other hand, queues follow the First-In-First-Out (FIFO) principle, where elements are added at one end, called the rear or tail, and removed from the other end, known as the front or head. This ensures that elements are processed in the order they were inserted, just like people waiting in a queue. Queues are commonly used in scenarios such as managing print jobs, implementing breadth-first search algorithms, or handling requests in a web server.</p><p>In Python, stacks can be implemented using lists or the built-in deque module, while queues can be implemented using lists or the deque module with the append and popleft methods. Here’s an example of how to implement a stack and a queue in Python:</p><pre># Implementing a stack using a list<br>stack = []<br>stack.append(1)  # Add element to the top of the stack<br>stack.append(2)<br>stack.append(3)<br>print(stack.pop())  # Remove and return the topmost element (prints 3)<br>print(stack.pop())  # prints 2<br>print(stack.pop())  # prints 1<br><br># Implementing a queue using the deque module<br>from collections import deque<br><br>queue = deque()<br>queue.append(1)  # Add element to the rear of the queue<br>queue.append(2)<br>queue.append(3)<br>print(queue.popleft())  # Remove and return the frontmost element (prints 1)<br>print(queue.popleft())  # prints 2<br>print(queue.popleft())  # prints 3</pre><p>Understanding how stacks and queues work is fundamental to mastering data structures in Python, as they provide a foundation for more complex data organization and manipulation. By leveraging these structures effectively, you can write more efficient and elegant code.</p><h3>4. Linked Lists: Dynamic Data Structures</h3><p>Linked lists are a fundamental data structure that offers dynamic storage and efficient operations for managing a collection of elements. Unlike arrays, linked lists do not require contiguous memory allocation, allowing for flexible resizing and insertion operations.</p><p>At its core, a linked list consists of nodes that are connected through pointers. Each node contains a data element and a pointer to the next node in the list. This sequential linking enables efficient traversal and manipulation of the elements.</p><p>Implementing a linked list in Python involves creating a Node class to represent the individual nodes and a LinkedList class to manage the collection. The Node class will have attributes for storing the data and a next pointer, while the LinkedList class will have methods for inserting, deleting, and searching for elements.</p><p>Here is an example of how a simple linked list can be implemented in Python:</p><pre>class Node:<br>    def __init__(self, data):<br>        self.data = data<br>        self.next = None<br><br>class LinkedList:<br>    def __init__(self):<br>        self.head = None<br><br>    def insert(self, data):<br>        new_node = Node(data)<br>        if self.head is None:<br>            self.head = new_node<br>        else:<br>            current = self.head<br>            while current.next:<br>                current = current.next<br>            current.next = new_node<br><br>    def display(self):<br>        current = self.head<br>        while current:<br>            print(current.data, end=&quot; -&gt; &quot;)<br>            current = current.next<br>        print(&quot;None&quot;)</pre><p>In this example, the LinkedList class has a head attribute that points to the first node in the list. The insert method inserts a new node at the end of the list, while the display method prints the elements in the list sequentially.</p><p>Linked lists provide a flexible and efficient way of managing dynamic data. They are particularly useful in scenarios where frequent insertions and deletions are required as they do not require shifting elements like arrays do.</p><h3>5. Trees and Graphs: Navigating and Organizing Complex Data</h3><p>In the world of data structures, trees and graphs play a pivotal role in organizing and managing complex data. Trees are hierarchical structures that consist of nodes connected by edges. The topmost node is called the root, and each node can have zero or more child nodes. Trees are commonly used to represent hierarchical relationships such as file systems, organizational structures, and family trees.</p><p>To illustrate the concept of trees, let’s consider a binary tree, where each node has at most two children. Here is an example of a binary tree implemented in Python:</p><pre>class Node:<br>    def __init__(self, value):<br>        self.value = value<br>        self.left_child = None<br>        self.right_child = None<br><br># Creating the root node<br>root = Node(1)<br><br># Creating the child nodes<br>root.left_child = Node(2)<br>root.right_child = Node(3)</pre><p>In this example, we create a `Node` class with a `value` property and left and right child pointers. We then instantiate the root node with a value of 1 and create its left and right child nodes with values 2 and 3, respectively. This creates a binary tree structure where the root is connected to its children.</p><p>Graphs, on the other hand, are more complex data structures that consist of nodes connected by edges. Unlike trees, graphs can have cyclic and bidirectional connections. They are commonly used to represent relationships between objects, such as social networks, internet connections, and road networks.</p><p>Implementing a graph in Python can be done using various techniques, including using an adjacency matrix or an adjacency list. Here’s an example of implementing a graph using an adjacency list:</p><pre>class Graph:<br>    def __init__(self, num_vertices):<br>        self.num_vertices = num_vertices<br>        self.adjacency_list = [[] for _ in range(num_vertices)]<br><br>    def add_edge(self, start_vertex, end_vertex):<br>        self.adjacency_list[start_vertex].append(end_vertex)<br>        self.adjacency_list[end_vertex].append(start_vertex)<br><br># Creating a graph with 5 vertices<br>graph = Graph(5)<br><br># Adding edges to the graph<br>graph.add_edge(0, 1)<br>graph.add_edge(0, 2)<br>graph.add_edge(1, 3)<br>graph.add_edge(2, 4)</pre><p>In this example, we create a `Graph` class with an adjacency list that keeps track of the connections between nodes. The `add_edge` method is used to add edges between nodes by updating the adjacency list accordingly.</p><p>Understanding and implementing trees and graphs is essential for mastering data structures, as they provide powerful ways to organize, search, and manipulate complex data. Through various algorithms and techniques, we can navigate and <strong>analyze</strong> the data stored in trees and graphs efficiently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f463369c648" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use SocketsBay Web Sockets with Flutter]]></title>
            <link>https://medium.com/@ldanadrian/how-to-use-socketsbay-web-sockets-with-flutter-9c5ab5f8de0e?source=rss-3584379beeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5ab5f8de0e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[realtime]]></category>
            <dc:creator><![CDATA[Lutescu Dan]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 10:05:11 GMT</pubDate>
            <atom:updated>2023-02-02T10:05:11.176Z</atom:updated>
            <content:encoded><![CDATA[<p>SocketsBay is a web socket service that provides real-time data communication for web and mobile applications. In this article, we will show you how to use the SocketsBay Web Socket API in a Flutter application using the code example provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbxyYdRWsPxR2vyaUztfzA.jpeg" /></figure><p>To use SocketsBay, you will first need to create an account on their website and obtain the Web Socket URL that you will use to connect to the service. The URL is stored in the socketsBayUrl constant in the code example.</p><p>The code example uses the WebSocketChannel class from the flutter_web_socket_channel package to connect to the SocketsBay service. The WebSocketChannel.connect method is used to create a Web Socket connection to the URL provided. The channel.stream is then listened to, so that the application can receive messages sent by the SocketsBay service.</p><p>The _connect method is used to connect to the SocketsBay service. If the connection is successful, the method sets the isConnected variable to true. If the connection fails, an error message is displayed.</p><p>The _sendMessage method is used to send messages to the SocketsBay service. The message is added to the sink of the Web Socket channel, and the messages list is updated to reflect the sent message.</p><p>The _onMessage and _onError methods are used to handle messages received from the SocketsBay service and any errors that occur during the Web Socket connection, respectively.</p><p>The Flutter widget tree contains a Scaffold widget with an AppBar and a Center widget. The Center widget contains a Column widget with several children, including a Container with a ListView displaying the messages received from the SocketsBay service. There are also two ElevatedButton widgets that allow the user to connect to the SocketsBay service and send messages.</p><p>In conclusion, using SocketsBay Web Sockets in a Flutter application is a straightforward process. With the help of the code example provided, you can easily implement real-time data communication in your Flutter application.</p><pre>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  final String socketsBayUrl = &quot;wss://socketsbay.com/wss/v2/1/demo/&quot;;<br><br>  late WebSocketChannel channel;<br>  bool isConnected = false;<br><br>  List&lt;String&gt; messages = [];<br><br>  _connect() {<br>    try {<br>      channel = WebSocketChannel.connect(<br>        Uri.parse(socketsBayUrl),<br>      );<br>      channel.stream.listen(_onMessage, onError: _onError);<br>      setState(() {<br>        isConnected = true;<br>      });<br><br>      print(&quot;Connected with success!&quot;);<br>    } on Exception catch (_) {<br>      print(&quot;ERROR! Cannot connect to host!&quot;);<br>    }<br>  }<br><br>  _sendMessage(String message) {<br>    channel.sink.add(message);<br>    setState(() {<br>      messages.add(message);<br>    });<br><br>    print(&quot;We sent: ${message}&quot;);<br>  }<br><br>  _onMessage(dynamic message) {<br>    setState(() {<br>      messages.add(message);<br>    });<br>    print(&quot;We have received: ${message}&quot;);<br>  }<br><br>  _onError(Object err) {<br>    print(&quot;we have an error: ${err}&quot;);<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(widget.title),<br>      ),<br>      body: Center(<br>        child: Column(<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: &lt;Widget&gt;[<br>              Container(<br>                color: Colors.blue,<br>                height: 200,<br>                child: ListView.builder(<br>                    itemCount: messages.length,<br>                    itemBuilder: (context, index) {<br>                      var item = messages[index];<br>                      return ListTile(<br>                          title: Text(item,<br>                              style: const TextStyle(color: Colors.black)));<br>                    }),<br>              ),<br>              isConnected<br>                  ? const Text(&quot;connected&quot;)<br>                  : ElevatedButton(<br>                      onPressed: (() =&gt; _connect()),<br>                      child: const Text(&quot;connect&quot;)),<br>              ElevatedButton(<br>                  onPressed: (() =&gt; _sendMessage(&quot;hello hello!&quot;)),<br>                  child: const Text(&quot;send message&quot;)),<br>            ]),<br>      ),<br>    );<br>  }<br>}</pre><p>In conclusion, using SocketsBay Web Sockets in a Flutter application is a straightforward process. With the help of the code example provided, you can easily implement real-time data communication in your Flutter application. If you’re interested in learning more, you can find the complete code on Git ( <a href="https://github.com/ldanadrian/sockets-bay-flutter-example">here</a> ), where you can also join the growing community of developers using SocketsBay.</p><p>With the right tools and a little bit of creativity, you can build powerful and engaging applications that can provide real-time data to your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5ab5f8de0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3+ WebSockets: How to build a realtime multiplayer game in 10 minutes]]></title>
            <link>https://medium.com/@ldanadrian/vue-3-websockets-how-to-build-a-realtime-multiplayer-game-in-10-minutes-cbee586dbfd0?source=rss-3584379beeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbee586dbfd0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[websocket-server]]></category>
            <dc:creator><![CDATA[Lutescu Dan]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 13:31:42 GMT</pubDate>
            <atom:updated>2022-12-14T13:43:42.845Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we will see how to quickly build a realtime multiplayer game application with using Vue 3 and a free <a href="https://socketsbay.com/">SocketsBay</a> account.</p><p>You will need a standard Vue3 project ( check the beginning of the article <a href="https://medium.com/@ldanadrian/vue-3-websockets-how-to-build-a-realtime-chat-application-in-15-minutes-3b6a8ae5c08b">here</a> ). After that, you will ned a free <a href="https://socketsbay.com/">SocketsBay</a> account for a free sockets server.</p><p>The result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F1d8VVfsrLMU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D1d8VVfsrLMU&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ae2cd051eb4567cbae8e574e544cc6b/href">https://medium.com/media/0ae2cd051eb4567cbae8e574e544cc6b/href</a></iframe><p>First of all we must build a server. Because we don’t wan’t to take care of the difficult manual server creation we will use only a <a href="https://socketsbay.com/">SocketsBay</a> account and a view called Server.vue</p><p>First, add a Client and a Server to the routes, in the “router/index.js” file:</p><pre>const routes = [<br>  { path: &#39;/server&#39;, name: &#39;server&#39;, component: () =&gt; import(&#39;../views/Server.vue&#39;) },<br>  { path: &#39;/client&#39;, name: &#39;client&#39;, component: () =&gt; import(&#39;../views/Client.vue&#39;) }<br>]</pre><p>We will create a base mode called Tank, in a file called Backend/Tank.js:</p><pre><br>class Tank{<br>    constructor( _tankId ){<br>        this.tank_id    = _tankId;<br>        this.x          = 0;<br>        this.y          = 0;<br>        this.rotation   = 0;<br>    }<br><br>    move_left(){<br>        this.x       -= 5;<br>        this.rotation = 90;<br>    }<br><br>    move_right(){<br>        this.x       += 5;<br>        this.rotation = -90;<br>    }<br><br>    move_up(){<br>        this.y       -= 5;<br>        this.rotation = 180;<br>    }<br><br>    move_down(){<br>        this.y += 5;<br>        this.rotation = 0;<br>    }<br>    send_to_server(socket) {<br>        var _data = { &quot;cmd&quot; : &quot;move_tank&quot;, &quot;tank_id&quot;: this.tank_id, &quot;x&quot;: this.x, &quot;y&quot;: + this.y, &quot;rotation&quot;: this.rotation };<br>        socket.send( JSON.stringify(_data) );<br>    }<br><br>}<br><br>module.exports = Tank // 👈 Export class</pre><p>Each tank has a X and a Y position, also it has a rotation ( in degrees ). We created a “send_to_server” method to send our new position when we move our tank.</p><h3>Server file</h3><p>Next, let’s create the Server vue file in “Views/Server.vue” like this:</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>      &lt;h1&gt;Server&lt;/h1&gt;<br>      &lt;h2 v-if=&quot;connected&quot;&gt;Connected&lt;/h2&gt;<br>      &lt;ul class=&quot;log&quot;&gt;<br>        &lt;li v-for=&quot;(log_item,idx) in log&quot; :key=&quot;&#39;log-&#39; + idx&quot;&gt;{{log_item}}&lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  &lt;/template&gt;<br><br>&lt;script&gt;<br>  import Tank from &#39;../backend/Tank.js&#39;;<br><br><br>  export default {<br>    name: &#39;Server&#39;,<br>    data() {<br>        return {<br>            tanks: [],<br>            connected: false,<br>            log:[],<br>            url: &#39;wss://socketsbay.com/wss/v2/1/demo/&#39;,<br>            socket: {},<br>        }<br>    },<br>    methods: {<br>        send_tank_list() {<br>            var _data = { &quot;cmd&quot; : &quot;list_tanks&quot;, &quot;tanks&quot;: this.tanks };<br>            this.socket.send( JSON.stringify(_data) );<br>        },<br>        init_server() {<br>            this.socket = new WebSocket(this.url);<br>            <br>            this.socket.onopen = () =&gt; {<br>                this.connected = true;<br>            };<br>            <br>            this.socket.onmessage = ( message ) =&gt; {<br>                var _data = JSON.parse(message.data);<br>                <br>                if( _data.cmd == &quot;new_tank&quot; ) {<br>                    this.tanks.push( new Tank( _data.tank_id) );<br>                    this.log.push(`Tank with id ${_data.tank_id} joined the game!`);<br>                    <br>                    this.send_tank_list();<br>                }<br>                if( _data.cmd == &quot;move_tank&quot; ) {<br>                    var tank        = this.tanks.find( x=&gt; x.tank_id == _data.tank_id );<br>                    tank.x          = _data.x;<br>                    tank.y          = _data.y;<br>                    tank.rotation   = _data.rotation;<br>                    //<br>                    this.send_tank_list();<br>                }<br>                if( _data.cmd == &quot;list_tanks&quot; ) {<br>                    this.send_tank_list();<br>                }<br>            };<br>        }<br>    },<br>    mounted(){<br>        this.init_server();<br>    }<br>  }<br>  &lt;/script&gt;<br>  <br>  &lt;style scoped lang=&quot;less&quot;&gt;<br>    ul.log{<br>        text-align: left;<br>    }<br>  &lt;/style&gt;</pre><p>The code should be self explanatory, but let’s split it into pieces:</p><ol><li>We store all the tanks in our game in the tanks array variable</li><li>We have the ‘connected’ variabile — <strong>true</strong> when the socket connection is realised</li><li>A log array, basically all the log messages that we want.</li></ol><p>When a client connects to a game, a new tank is added to the tanks array. Also, when we move a tank, the new position is sent to all the connected clients.</p><h3>Now for the client code</h3><p>The html part should look like this:</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;h1&gt;Client&lt;/h1&gt;<br>        &lt;h2 v-if=&quot;connected&quot;&gt;Connected&lt;/h2&gt;<br>        &lt;div class=&quot;scene&quot;&gt;<br>            &lt;!-- other tanks --&gt;<br>            &lt;div class=&quot;tank&quot; v-for=&quot;(t,idx) in tanks&quot; :style=&quot;{ left: t.x + &#39;px&#39;, top: t.y + &#39;px&#39;, transform: &#39;rotate(&#39; + t.rotation + &#39;deg)&#39;}&quot; :key=&quot;&#39;tank-&#39; + idx&quot;&gt;<br>                &lt;div class=&quot;tank_id&quot;&gt;{{t.tank_id}}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;!-- our tank --&gt;<br>            &lt;div class=&quot;tank&quot; :style=&quot;{ left: my_tank.x + &#39;px&#39;, top: my_tank.y + &#39;px&#39;, transform: &#39;rotate(&#39; + my_tank.rotation + &#39;deg)&#39;}&quot;&gt;<br>                &lt;div class=&quot;tank_id&quot;&gt;{{my_tank.tank_id}}&lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/template&gt;</pre><p>Here we have a scene, the other player tanks and our tank. Let’s add some css to this, and also some game elements from this wonderful <a href="https://opengameart.org/">website</a>. I used the background from <a href="https://opengameart.org/content/16x16-rpg-tileset">here</a> and the tank from this <a href="https://opengameart.org/content/mediumtanks">package</a>, but feel free to search for others.</p><pre>&lt;style scoped lang=&quot;less&quot;&gt;<br>    .scene{<br>        border: 1px solid black;<br>        margin: 20px auto;<br>        position: relative;<br>        height: 640px;<br>        width: 960px;<br>        background: url(https://medium.com/assets/background.png);<br>        overflow: hidden;<br>    }<br>    .tank{<br>        position: absolute;<br>        width: 76px;<br>        height: 89px;<br>        background: url(https://medium.com/assets/tank1.png);<br>        transition: 0.3s all linear;<br>        .tank_id{<br>            position: absolute;<br>            left: 0;<br>            right: 0;<br>            top: -20px;<br>            height: 20px;<br>            background: black;<br>            color: white;<br>            line-height: 20px;<br>            opacity: 0.7;<br>        }<br>    }<br>  &lt;/style&gt;</pre><p>Okay, done that, now let’s make the javascript who will listen for new tanks and new tanks positions:</p><pre>&lt;script&gt;<br>  import Tank from &#39;../backend/Tank.js&#39;;<br><br>  export default {<br>    name: &#39;Server&#39;,<br>    data() {<br>        return {<br>            tanks: [],  //other tanks<br>            my_tank: {},<br>            connected: false,<br>            my_id: &quot;&quot;,<br>            url: &#39;wss://socketsbay.com/wss/v2/1/demo/&#39;,<br>            socket: {},<br>            <br>        }<br>    },<br>    methods: {<br>        init_server() {<br>            this.socket = new WebSocket(this.url);<br>            <br>            this.socket.onopen = () =&gt; {<br>                this.connected = true;<br>                //send my tank info!<br>                this.my_tank = new Tank( this.my_id );<br>                var _data    = { cmd: &quot;new_tank&quot;, tank_id: this.my_id };<br>                this.socket.send( JSON.stringify(_data) );<br>            };<br>            <br>            this.socket.onmessage = ( message ) =&gt; {<br>                var _data = JSON.parse(message.data);<br>                if( _data.cmd == &quot;list_tanks&quot; ){<br>                    this.tanks = _data.tanks.filter( x=&gt; x.tank_id != this.my_id );<br>                }<br>            };<br><br>        }<br>    },<br>    mounted(){<br>        this.my_id = prompt(&#39;Tank name, commander?&#39;);<br>        this.init_server();<br>    }<br>  }<br>  &lt;/script&gt;</pre><p>Easy, right? Just send your tank information when you connect, and when you receive a new “list” of tanks from the server just update it.</p><p>Okay, now we need to move the tank using arrows. For that, just add this code in the init_server() method:</p><pre> window.onkeydown = (e) =&gt; {<br>    var key     = e.keyCode ? e.keyCode : e.which;<br>    <br>    // key down<br>    if( key == 40 ) { this.my_tank.move_down (); this.my_tank.send_to_server(this.socket); }<br>    // key up<br>    if( key == 38 ) { this.my_tank.move_up   (); this.my_tank.send_to_server(this.socket); }<br>    // key left<br>    if( key == 37 ) { this.my_tank.move_left (); this.my_tank.send_to_server(this.socket); }<br>    // key right<br>    if( key == 39 ) { this.my_tank.move_right(); this.my_tank.send_to_server(this.socket); }<br>}</pre><p>Congratulations! Now you have a real multiplayer functional game. So now the code should look like this:</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;h1&gt;Client&lt;/h1&gt;<br>        &lt;h2 v-if=&quot;connected&quot;&gt;Connected&lt;/h2&gt;<br>        <br>        <br>        &lt;div class=&quot;scene&quot;&gt;<br>            &lt;div class=&quot;tank&quot; v-for=&quot;(t,idx) in tanks&quot; :style=&quot;{ left: t.x + &#39;px&#39;, top: t.y + &#39;px&#39;, transform: &#39;rotate(&#39; + t.rotation + &#39;deg)&#39;}&quot; :key=&quot;&#39;tank-&#39; + idx&quot;&gt;<br>                &lt;div class=&quot;tank_id&quot;&gt;{{t.tank_id}}&lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;tank&quot; :style=&quot;{ left: my_tank.x + &#39;px&#39;, top: my_tank.y + &#39;px&#39;, transform: &#39;rotate(&#39; + my_tank.rotation + &#39;deg)&#39;}&quot;&gt;<br>                &lt;div class=&quot;tank_id&quot;&gt;{{my_tank.tank_id}}&lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/template&gt;<br>  <br>  &lt;script&gt;<br>  import Tank from &#39;../backend/Tank.js&#39;;<br><br><br>  export default {<br>    name: &#39;Server&#39;,<br>    data() {<br>        return {<br>            tanks: [],  //other tanks<br>            my_tank: {},<br>            connected: false,<br>            my_id: &quot;&quot;,<br>            url: &#39;wss://socketsbay.com/wss/v2/1/demo/&#39;,<br>            socket: {},<br>            <br>        }<br>    },<br>    methods: {<br>        init_server() {<br>            this.socket = new WebSocket(this.url);<br>            <br>            this.socket.onopen = () =&gt; {<br>                this.connected = true;<br>                //send my tank info!<br>                this.my_tank = new Tank( this.my_id );<br>                var _data    = { cmd: &quot;new_tank&quot;, tank_id: this.my_id };<br>                this.socket.send( JSON.stringify(_data) );<br>            };<br>            <br>            this.socket.onmessage = ( message ) =&gt; {<br>                var _data = JSON.parse(message.data);<br>                if( _data.cmd == &quot;list_tanks&quot; ){<br>                    this.tanks = _data.tanks.filter( x=&gt; x.tank_id != this.my_id );<br>                }<br>            };<br><br>            window.onkeydown = (e) =&gt; {<br>                var key     = e.keyCode ? e.keyCode : e.which;<br>                <br>                // //key down<br>                if( key == 40 ) { this.my_tank.move_down (); this.my_tank.send_to_server(this.socket); }<br>                //key up<br>                if( key == 38 ) { this.my_tank.move_up   (); this.my_tank.send_to_server(this.socket); }<br>                //key left<br>                if( key == 37 ) { this.my_tank.move_left (); this.my_tank.send_to_server(this.socket); }<br>                // //key right<br>                if( key == 39 ) { this.my_tank.move_right(); this.my_tank.send_to_server(this.socket); }<br>            }<br>        }<br>    },<br>    mounted(){<br>        this.my_id = prompt(&#39;Tank name, commander?&#39;);<br>        this.init_server();<br>    }<br>  }<br>  &lt;/script&gt;<br>  <br>  &lt;style scoped lang=&quot;less&quot;&gt;<br>    .scene{<br>        border: 1px solid black;<br>        margin: 20px auto;<br>        position: relative;<br>        height: 640px;<br>        width: 960px;<br>        background: url(https://medium.com/assets/background.png);<br>        overflow: hidden;<br>    }<br>    .tank{<br>        position: absolute;<br>        width: 76px;<br>        height: 89px;<br>        background: url(https://medium.com/assets/tank1.png);<br>        transition: 0.3s all linear;<br>        .tank_id{<br>            position: absolute;<br>            left: 0;<br>            right: 0;<br>            top: -20px;<br>            height: 20px;<br>            background: black;<br>            color: white;<br>            line-height: 20px;<br>            opacity: 0.7;<br>        }<br>    }<br>  &lt;/style&gt;</pre><h3>Testing the game</h3><p>Just start the server in a browser tab with <a href="http://localhost:8080/#/server">http://localhost:8080/#/server</a> and open the client on other computers ( or the same ) <a href="http://localhost:8080/#/client">http://localhost:8080/#/client</a> ( replace localhost with your ip ) and.. start moving the tanks with the arrow keys.</p><h3>In conclusion…</h3><p>WebSockets are the best solution for realtime multiplayer games running in a web browser. Once the connection is established, WebSockets offer the lowest latency connection mechanism for bi-directional communication between a server and a client.</p><p>The real-time web is evolving, and the WebSocket protocol is a crucial cog in its evolution. Go forth and use it for good!</p><h3>You can also find the code on GitHub:</h3><p><a href="https://github.com/ldanadrian/sockets-bay-realtime-multiplayer-game-tanks">GitHub - ldanadrian/sockets-bay-realtime-multiplayer-game-tanks: Vue 3+ WebSockets: How to build a realtime multiplayer game in 10 minutes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbee586dbfd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue 3+ WebSockets: How to build a realtime chat application in 15 minutes]]></title>
            <link>https://medium.com/@ldanadrian/vue-3-websockets-how-to-build-a-realtime-chat-application-in-15-minutes-3b6a8ae5c08b?source=rss-3584379beeda------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b6a8ae5c08b</guid>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Lutescu Dan]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 13:34:49 GMT</pubDate>
            <atom:updated>2022-11-22T14:09:54.593Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we will see how to quickly build a realtime chat application with an authentication system using Vue 3, vue-router and a free SocketsBay account.</p><h3>What is Vue.js ?</h3><p>Here is an overview of this amazing and lightweight javascript framework:</p><blockquote>Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.</blockquote><h3>What is a WebSocket ?</h3><p><strong>WebSocket</strong> is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol enables interaction between a web browser (or other client application) and a web server with lower overhead than half-duplex alternatives such as HTTP polling, facilitating real-time data transfer from and to the server.</p><p>This is made possible by providing a standardised way for the server to send content to the client without being first requested by the client, and allowing messages to be passed back and forth while keeping the connection open. In this way, a two-way ongoing conversation can take place between the client and the server.</p><p>The communications are done over TCP port number 80 (or 443 in the case of TLS-encrypted connections), which is of benefit for those environments which block non-web Internet connections using a firewall.</p><h3>What is SocketsBay.com ?</h3><p>It is a free service allowing you to create a WebSocket server without the pain of configuring the server. In just a few minutes you can have a working secure web socket server. That way, you can focus on your app and users. For this tutorial you have to prepare a <a href="https://socketsbay.com/">free account</a> here.</p><h3>Let’s start !</h3><p>First, we are going to initialise a new Vue project by using the great tool <strong>Vue Cli </strong>( <a href="https://cli.vuejs.org/">https://cli.vuejs.org/</a> )<em>. </em>At the time of the article, last version is <strong>5.0.8</strong></p><p>If you don’t already have <strong>vue cli</strong> installed, let’s install it:</p><pre>npm install -g @vue/cli</pre><p>Now that you have <strong>vue cli</strong> installed, let’s create a new project.</p><pre>vue create vue-chat</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*1edL16frfqOtttMcrrnMAA.jpeg" /></figure><p>choose “Manually select features” and check the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*qWwoyapqU9oFWNIPX6jOIQ.jpeg" /></figure><p>Choose Babel, Router, Vuex and ( optionally ) CSS Pre-processors. Press Enter key after.</p><pre><strong>Use history mode for router? (Requires proper server setup for index fallback in production)</strong> (Y/n) </pre><p>Press “Y” and after that the Enter key.</p><p>If you checked the CSS Pre-processors, the wizard will now ask you what preprocessor would you like. I’m a LESS fan, so just choose LESS and press Enter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFKpV63HcrWLHocm24iI7w.jpeg" /></figure><p>At the next question just answer whatever you want, it is not relevant for our tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vOAIaB9yYNH8IizLyT6Ug.jpeg" /></figure><p>And — finally:</p><pre><strong>Save this as a preset for future projects?</strong> (y/N)</pre><p>just press ’n’ and Enter to start installing everything you need!</p><p>After this, just write</p><pre>cd vue-chat</pre><p>and start the application</p><pre>vue run serve</pre><p>and if everything was all right, the browser will start at the url ‘<strong>http://localhost:8080</strong>’ and the default Vue page will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5eQPCzdLMdGNHZH6Mx99w.jpeg" /><figcaption>Default Vue starting page</figcaption></figure><h3>Now let’s prepare our project !</h3><p>Before building the chat page, we need to create a new app in our <a href="https://socketsbay.com/">SocketsBay</a> account. Click on the “Create new app” button in your account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFppqDXA9ljMCwg-aqK3xw.jpeg" /><figcaption>Click on the “Create new app” button in your account</figcaption></figure><p>You will receive a API key and we will keep it in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wC0wooANlzhsmU7H5tXUMg.jpeg" /></figure><p>Now let’s get back to our project! Follow the next steps to clean our code a little:</p><p>1. Delete the <strong>src/components</strong> folder! we don’t need it<br>2. Delete the <strong>src/views/AboutView.vue</strong> file! we don’t need it <br>3. In the file <strong>src/router/index.js</strong> delete the part with “about”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WXVP6CMRCSZCk6wy7eN1A.jpeg" /><figcaption>remove this part of code, we don’t need it :)</figcaption></figure><p>4. In the file src/App.vue, delete this upper html code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mc3y-tHhD6OMAt1NRmBhBQ.jpeg" /><figcaption>remove this part also</figcaption></figure><p>5. Delete everything in the <strong>src/views/HomeView.vue</strong> file and write this instead:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    Here we will write our awesome code!  <br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script&gt;<br>export default {<br>  name: &#39;HomeView&#39;,<br>  <br>}<br>&lt;/script&gt;<br><br>&lt;style lang=&quot;less&quot;&gt;<br>&lt;/style&gt;</pre><h3>Verification:</h3><p>Save and check the url <a href="http://localhost:8080/">http://localhost:8080/</a> and if you see something like this, everything is ready:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yf4IGLPGYsjVNvL8y9IOtQ.jpeg" /><figcaption>ready for action!</figcaption></figure><h3>Add an image asset to the code</h3><p>Just “<em>save as</em>” this image and save it in <strong>src/assets/background.jpg</strong> folder from your project. Alternatively you can download the image from <a href="https://github.com/ldanadrian/sockets-bay-vuejs-chat/raw/main/src/assets/background.jpg">here</a>. It’s nice and it will make your work more good looking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*ZZuySUVUAN0bnBfnPwwT3Q.jpeg" /></figure><h3>Perfect! Now let’s write some code!</h3><p>Now, everything that we will do it will be in <strong>src/views/HomeView.vue</strong> file.</p><p>First step is to add our variables. Let’s add this in the data part of the vue component:</p><pre>data(){<br>    return {<br>      sockets_bay_api_key: &quot;&quot;, //here you must insert your api key from Sockets Bay<br>      connection_ready: false,<br>      connection_error: false,<br>      nickname: &quot;&quot;,<br>      websocket: null,<br>      new_message: &quot;&quot;,<br>      messages: []<br>    }<br>  },</pre><p>the code is self explanatory. We keep the nickname of the connected user, the connection status and the messages displayed on the screen.</p><p>Now let’s add the html code. It is divided in 3 parts:</p><ol><li>the header part ( title and connection status )</li><li>the chat message list</li><li>the sending part ( where we write and send messages )</li></ol><pre>&lt;template&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>      &lt;h1&gt;Awesome chat - &lt;span class=&quot;connection_ready&quot; v-if=&quot;connection_ready&quot;&gt;Connection ready!&lt;/span&gt;&lt;/h1&gt;<br>      <br>      &lt;div class=&quot;messages&quot; id=&quot;messages&quot;&gt;<br>        &lt;div class=&quot;message-container&quot;&gt;<br>          &lt;h1 class=&quot;error&quot; v-if=&quot;connection_error&quot;&gt; Connection error! &lt;/h1&gt;<br>          &lt;div v-for=&quot;(m,idx) in messages&quot; :key=&quot;&#39;m-&#39; + idx&quot; style=&quot;clear:both&quot;&gt;<br>            &lt;div :class=&quot;{ &#39;msg-from-me&#39; : m.from==&#39;me&#39;, &#39;msg-from-other&#39; : m.from==&#39;other&#39;}&quot;&gt;<br>              {{m.message}}<br>            &lt;/div&gt;<br>          &lt;/div&gt; <br>        &lt;/div&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;send-zone&quot;&gt;<br>        &lt;input v-model=&quot;new_message&quot; type=&quot;text&quot; placeholder=&quot;Type a message&quot; @keyup.enter=&quot;send_message&quot;/&gt;<br>      &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>For a quick preview, it should look like this at the end:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBcA2eCoidNCcqQxvJOVSw.jpeg" /></figure><p>But to get this app to be that pretty, we have to add this CSS code, in the style part:</p><pre>&lt;style lang=&quot;less&quot;&gt;<br>  body{<br>    background: #111b21;<br>  }<br>  .container{<br>    display: flex;<br>    flex-direction: column;<br>    margin: 0 auto;<br>    max-width: 768px;<br>    min-height: 98vh;<br>    position: relative;<br><br>    h1{<br>      padding: 0px;<br>      height: 20px;<br>      color: white;<br>      font-size: 20px;<br>      text-transform: uppercase;<br><br>      .connection_ready{<br>        color: greenyellow;<br>      }<br>    }<br><br>    .messages{<br>      height: 80vh;<br>      overflow-y: scroll;<br>      background: url(https://medium.com/@/assets/background.jpg) no-repeat center;<br>      background-size: cover;<br><br>      .msg-from-me {<br>        border-radius: 7.5px;<br>        max-width: 65%;<br>        font-size: 16px;<br>        line-height: 19px;<br>        color: #e9edef;<br>        background: fade( #046a62, 90%);<br>        padding: 5px;<br>        margin: 20px 20px 5px 0px;<br>        <br>        float: right;<br>      }<br>      .msg-from-other {<br>        border-radius: 7.5px;<br>        max-width: 65%;<br>        font-size: 16px;<br>        line-height: 19px;<br>        color: #e9edef;<br>        background: fade( #202c33, 90%);<br>        padding: 5px;<br>        margin: 20px 0px 5px 20px;<br>        float: left;<br>      }<br>    }<br>    .send-zone{<br>      height: 62px;<br>      background: #202c33;<br>      display: flex;<br><br>      input[type=&#39;text&#39;]{<br>        padding: 9px 12px 11px;<br>        margin: 5px 10px;<br>        border: 1px solid #2a3942;<br>        background: #2a3942;<br>        border-radius: 8px;<br>        font-size: 15px;<br>        flex-grow: 1;<br>        color: white;<br>      }<br><br>    }<br>  }<br>  <br>&lt;/style&gt;</pre><p>Good ! now the app is looking great! And now, for the functionality:</p><pre>export default {<br>  name: &#39;HomeView&#39;,<br>  data(){<br>    return {<br>      sockets_bay_api_key: &quot;&quot;, //here you must insert your api key from Sockets Bay<br>      connection_ready: false,<br>      connection_error: false,<br>      nickname: &quot;&quot;,<br>      websocket: null,<br>      new_message: &quot;&quot;,<br>      messages: []<br>    }<br>  },<br>  methods:{<br>    init_chat() {<br>      //ask for a nickname<br>      if(this.nickname == &quot;&quot;) this.nickname = prompt(&quot;Enter a nickname:&quot;);<br><br>      //connect to Sockets Bay<br>      var sockets_bay_url = `wss://socketsbay.com/wss/v2/100/${this.sockets_bay_api_key}/`;<br>      this.websocket      = new WebSocket(sockets_bay_url);<br>      //<br>      this.websocket.onopen    = this.onSocketOpen;<br>      this.websocket.onmessage = this.onSocketMessage;<br>      this.websocket.onerror   = this.onSockerError;<br>    },<br>    onSocketOpen(evt){<br>      this.connection_ready = true;<br>    },<br>    onSocketMessage(evt){<br>      //we parse the json that we receive<br>      var received = JSON.parse(evt.data);<br>      //check if it&#39;s our message or from a friend<br>      this.messages.push( { from: &quot;other&quot;, message: received.message } );<br>      //scroll to the bottom of the messages div<br>      const messages_div = document.getElementById(&#39;messages&#39;);<br>      messages_div.scrollTo({top: messages_div.scrollHeight, behavior: &#39;smooth&#39;});<br>    },<br><br>    onSockerError(evt){<br>      this.connection_error = true;<br>    },<br><br>    send_message() {<br>      var to_send = { from: this.nickname, message: this.new_message };<br>      this.websocket.send( JSON.stringify(to_send) );<br>      this.messages.push( { from: &quot;me&quot;   , message: this.new_message } );<br>      this.new_message = &quot;&quot;;<br>    }<br>  },<br>  mounted() {<br>    this.init_chat();<br>  }<br>}</pre><p>Some code explinations:</p><p>When the page is mounted, we call init_chat method. This one establish connection with the sockets server and sets up the methods:</p><ol><li>onSocketOpen -&gt; this method is called when the connection to the WebSocket server is opened. Here we just made the connection_ready variable true, to show the <strong>CONNECTION READY! </strong>message in the header</li><li>onSocketMessage -&gt; this method is called when we receive a message from the WebSocket server. Because we send messages as JSON packages, we first parse the json string received and then we decide if we add the message as our message or as on “other” friend message. And we just add this to our messages array. Vue will take care of the rest :)</li><li>onSocketError -&gt; this method is called when we have a connection problem. In this example it will just show a message in the chat area with a “Connection error!” message</li></ol><p>On the text input we called the method “send_message” when we press the enter key. This method creates a json with this template:</p><pre>{ from: &quot;sender&#39;s nickname&quot;, message: &quot;his message to the world!&quot;}</pre><p>and we just send it to the SocketsBay server using the send method.</p><h3>Let’s see it in action!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUYe_P7RNaGg&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUYe_P7RNaGg&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FUYe_P7RNaGg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3febe98dcec37300ad6b7138f434650/href">https://medium.com/media/f3febe98dcec37300ad6b7138f434650/href</a></iframe><h3>You can also find the code on GitHub:</h3><p><a href="https://github.com/ldanadrian/sockets-bay-vuejs-chat">GitHub - ldanadrian/sockets-bay-vuejs-chat: Vue 3 + WebSockets: Realtime chat application using SocketsBay.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b6a8ae5c08b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>