Python Programming Websockets

Python programming websockets

Python Websockets Server Program

This python server websocket program, websockets calls the handler 'chat' once for each WebSocket connection request.

Websocket connection is closed when the handler completes the execution.

#!/usr/bin/env python

import asyncio
import websockets

async def chat(websocket, path):
	while(True):
    	msg = await websocket.recv()
    	print(f"From Client: {msg}")

    	msg = input("Enter message to client(type 'q' to exit): ")
    	if msg == "q":
        	break;
    	await websocket.send(msg)

start_server = websockets.serve(chat, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Python Websockets Client Program

In this python websocket client program, ensures closing the connection once handler chat execution is completed since using websocket connect method as an asynchronous context manager.

#!/usr/bin/env python

import asyncio
import websockets

async def chat():
	async with websockets.connect(
        	'ws://localhost:8765') as websocket:
    	while(True):
        	msg = input("Enter message to server (type 'q' to exit):")
        	if msg == "q":
            	break;
        	await websocket.send(msg)

        	msg = await websocket.recv()
        	print(f"From Server: {msg}")

asyncio.get_event_loop().run_until_complete(chat())

python3 should be the default python version and python version should be 3.6 or greater version.

Install python websockets before running this python websockets server and client programs.

pip install websockets
Output:

Server:

$ python ws_server.py
From Client: hi
Enter message to client(type 'q' to exit): hi client1
From Client: how r u?
Enter message to client(type 'q' to exit): fine, and you?
Error in connection handler
Traceback (most recent call last):
  File "/usr/local/lib64/python3.6/site-packages/websockets/server.py", line 152, in handler
	yield from self.ws_handler(self, path)
  File "ws_server.py", line 10, in hello
	msg = await websocket.recv()
  File "/usr/local/lib64/python3.6/site-packages/websockets/protocol.py", line 350, in recv
	yield from self.ensure_open()
  File "/usr/local/lib64/python3.6/site-packages/websockets/protocol.py", line 512, in ensure_open
	self.close_code, self.close_reason) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1000 (OK), no reason

Client:

$ python ws_client.py
Enter message to server (type 'q' to exit):hi
From Server: hi client1
Enter message to server (type 'q' to exit):how r u?
From Server: fine, and you?
Enter message to server (type 'q' to exit):q

Python Programming Websockets chatting with no ssl certificate

Python Websockets Server Program

#!/usr/bin/env python

import asyncio
import pathlib
import ssl
import websockets

async def chat(websocket, path):
	while(True):
    	msg = await websocket.recv()
    	print(f"From Client: {msg}")

    	msg = input("Enter message to client(type 'q' to exit): ")
    	if msg == "q":
        	break;
    	await websocket.send(msg)

start_server = websockets.serve(
	chat, 'localhost', 8765, ssl=None)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Python Websockets Client Program

#!/usr/bin/env python

import asyncio
import pathlib
import ssl
import websockets

async def chat():
	async with websockets.connect(
        	'wss://localhost:8765', ssl=None) as websocket:
    	while(True):
        	msg = input("Enter message to server (type 'q' to exit):")
        	if msg == "q":
            	break;
        	await websocket.send(msg)

        	msg = await websocket.recv()
        	print(f"From Server: {msg}")

asyncio.get_event_loop().run_until_complete(chat())
Output:

Server:

 python ws_server_sec.py
From Client: hi
Enter message to client(type 'q' to exit): how are you?
Error in connection handler
Traceback (most recent call last):
  File "/usr/local/lib64/python3.6/site-packages/websockets/server.py", line 152, in handler
	yield from self.ws_handler(self, path)
  File "ws_server_sec.py", line 10, in chat
	msg = await websocket.recv()
  File "/usr/local/lib64/python3.6/site-packages/websockets/protocol.py", line 350, in recv
	yield from self.ensure_open()
  File "/usr/local/lib64/python3.6/site-packages/websockets/protocol.py", line 512, in ensure_open
	self.close_code, self.close_reason) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1000 (OK), no reason

Client:

$ python ws_client_sec.py
Enter message to server (type 'q' to exit):hi
From Server: how are you?
Enter message to server (type 'q' to exit):q

Python Programming Websockets chatting with Secure SSL Certificate

Python Websockets Server Program

#!/usr/bin/env python

import asyncio
import pathlib
import ssl
import websockets

async def chat(websocket, path):
	while(True):
    	msg = await websocket.recv()
    	print(f"From Client: {msg}")

    	msg = input("Enter message to client(type 'q' to exit): ")
    	if msg == "q":
        	break;
    	await websocket.send(msg)

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(
	pathlib.Path(__file__).with_name('localhost.pem'))

start_server = websockets.serve(
	chat, 'localhost', 8765, ssl=ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Python Websockets Client Program

#!/usr/bin/env python

import asyncio
import pathlib
import ssl
import websockets

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_verify_locations(
	pathlib.Path(__file__).with_name('localhost.pem'))

async def chat():
	async with websockets.connect(
        	'wss://localhost:8765', ssl=ssl_context) as websocket:
    	while(True):
        	msg = input("Enter message to server (type 'q' to exit):")
        	if msg == "q":
            	break;
        	await websocket.send(msg)

        	msg = await websocket.recv()
        	print(f"From Server: {msg}")

asyncio.get_event_loop().run_until_complete(chat())

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^