create web socket and save data in a text file

Today, we will create a websocket in linux and save the data received in a text file.webrtc implementation asterisk : Webphone

To create a WebSocket server in Linux that listens for incoming WebSocket connections and saves the received data to a text file, you can use Python with the websockets library. Below is a step-by-step guide to setting up this WebSocket server.

Steps:

  1. Install Python and websockets Library If Python is not installed, you can install it with the following command:
sudo apt-get install python3

Install the websockets library:

pip3 install websockets

Create WebSocket Server Script

Below is a simple Python WebSocket server that listens for incoming connections and writes any received data to a text file.

#!/usr/bin/env python3

import asyncio
import websockets

# Path to the file where data will be saved
output_file = 'received_data.txt'

async def save_to_file(data):
    # Append the received data to the file
    with open(output_file, 'a') as f:
        f.write(data + '\n')

async def handler(websocket, path):
    async for message in websocket:
        print(f"Received message: {message}")
        await save_to_file(message)

# Start the WebSocket server on localhost and port 8000
async def start_server():
    server = await websockets.serve(handler, 'localhost', 8000)
    await server.wait_closed()

# Run the WebSocket server
if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(start_server())
    asyncio.get_event_loop().run_forever()

Explanation:

  • The script defines a WebSocket server that listens on localhost port 8000.
  • For each incoming WebSocket message, the script saves the data into a text file (received_data.txt).
  • It uses the websockets.serve method to create the server, and asyncio to handle asynchronous operations.
  • Each time a message is received, it is saved in the received_data.txt file, appending each message on a new line.

Run the WebSocket Server

Save the Python script (e.g., websocket_server.py) and make it executable:

chmod +x websocket_server.py

Then, run the WebSocket server:

./websocket_server.py

The WebSocket server will now be running on ws://localhost:8000, and it will listen for incoming connections and save any received data into the received_data.txt file.

Test the WebSocket Server

You can test the server by creating a WebSocket client that sends data. Here’s a simple example using Python:

import asyncio
import websockets

async def send_message():
    uri = "ws://localhost:8000"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, WebSocket!")
        print("Message sent!")

asyncio.get_event_loop().run_until_complete(send_message())

After running this client, the message "Hello, WebSocket!" will be sent to the WebSocket server, and you will find it in the received_data.txt file.

Conclusion:

This setup allows you to create a WebSocket server in Linux that writes any received messages to a text file. You can expand this by handling different types of data or using it in larger applications that require persistent logging of WebSocket data.

Leave a Reply