29 เมษายน 2558

Published เมษายน 29, 2558 by with 0 comment

WebSocket กับ Python

สวัสดีผู้อ่านทุกท่านครับ บทความนี้ผมจะพาผู้อ่านไปแนะนำ WebSockets กับ Python กันครับ


WebSocket คืออะไร?
WebSocket เป็น API ที่สร้างการเชื่อมต่อแบบ (เกือบ) ถาวรระหว่างเซิฟเวอร์กับไคลเอนต์ ทำให้ทั้งสองผ่ายส่งข้อมูลกันได้ตลอด โดยอาคัยโพรโตคอล TCP แต่ไมได้รันบนโพรโตคอล HTTP
โดย WebSocket มี address ขึ้นต้นด้วย
ws://
และแบบเข้ารหัส
wss://

ภาษา Python ได้มีนักพัฒนา พัฒนาโมดูลสำหรับ WebSocket ออกมา นั้นคือ โมดูล websockets ครับ
โมดูล websockets

  • รองรับ Python 3.3 + ขึ้นไป (ไม่รองรับ Python 2)

  • ใช้ BSD License

  • เข้ากันได้กับมาตรฐาน WebSocket Protocol (RFC 6455)

  • ต้องการไลบรารี asyncio อ่านเพิ่มเติมได้ที่ Asynchronous I/O กับ Python ด้วย asyncio

สามารถติดตั้งได้โดยใช้คำสั่ง pip:
pip install websockets

ตัวอย่างการใช้งาน
ไฟล์ websocket_server.py


import asyncio
import websockets

@asyncio.coroutine
def hello(websocket, path):
 name = yield from websocket.recv()
 print("< {}".format(name))
 greeting = "Hello {}!".format(name)
 yield from websocket.send(greeting)
 print("> {}".format(greeting))

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

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


ไฟล์ websocket_client.py


import asyncio
import websockets

@asyncio.coroutine
def hello():
 websocket = yield from websockets.connect('ws://localhost:8765/')
 name = input("What's your name? ")
 yield from websocket.send(name)
 print("> {}".format(name))
 greeting = yield from websocket.recv()
 print("< {}".format(greeting))

asyncio.get_event_loop().run_until_complete(hello())


เวลารันโค้ดให้รันไฟล์ websocket_server.py ก่อนครับ แล้วจึงรันไฟล์ websocket_client.py ครับ
ผลลัพธ์

WebSocket กับ Python

อ่านเอกสารการใช้งานโมดูล websockets ใน Python ได้ที่ https://aaugustin.github.io/websockets/
ติดตามบทความต่อไปนะครับ
ขอบคุณครับ

0 ความคิดเห็น:

แสดงความคิดเห็น

แสดงความคิดเห็นได้ครับ :)