Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Create a WebSocket Server on macOS

WebSockets are a powerful technology that allows for real-time, bi-directional communication between a client and a server. This is particularly useful for applications that require constant updates, such as chat applications, live sports scores, or online gaming. In the Apple environment, specifically macOS, setting up a WebSocket server can be done efficiently using Node.js. This article will guide you through the process of creating a WebSocket server on macOS, providing practical examples and commands to help you get started.

Examples:

  1. Install Node.js and npm: First, ensure you have Node.js and npm (Node Package Manager) installed on your macOS system. You can install them using Homebrew, a popular package manager for macOS.

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    brew install node
  2. Create a new project directory: Create a new directory for your WebSocket server project and navigate into it.

    mkdir websocket-server
    cd websocket-server
  3. Initialize a new Node.js project: Initialize a new Node.js project using npm. This will create a package.json file in your project directory.

    npm init -y
  4. Install the WebSocket library: Install the ws library, a simple and efficient WebSocket library for Node.js.

    npm install ws
  5. Create the WebSocket server: Create a new file named server.js and add the following code to set up your WebSocket server.

    const WebSocket = require('ws');
    
    const server = new WebSocket.Server({ port: 8080 });
    
    server.on('connection', (socket) => {
     console.log('Client connected');
    
     socket.on('message', (message) => {
       console.log(`Received: ${message}`);
       socket.send(`Echo: ${message}`);
     });
    
     socket.on('close', () => {
       console.log('Client disconnected');
     });
    });
    
    console.log('WebSocket server is running on ws://localhost:8080');
  6. Run the WebSocket server: Start your WebSocket server by running the following command in your terminal.

    node server.js

    You should see the message "WebSocket server is running on ws://localhost:8080" in your terminal.

  7. Test the WebSocket server: You can test your WebSocket server using a WebSocket client. For simplicity, you can use a browser-based WebSocket client like the one available at https://www.websocket.org/echo.html. Connect to ws://localhost:8080 and send messages to see the echo responses from your server.

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.