Alex Tereshenkov
Alex Tereshenkov

Reputation: 3620

Connect to web socket (wss) with standard modules in Python?

I have used Python external package, websocket-client to connect to a RESTful service that sends events.

from websocket import create_connection
ws = create_connection("wss://machine:port/servicename/subscribe")

for event in ws:
    print event

...getting events printed

I wonder whether the same functionality can be implemented using the core Python 2.7 or Python 3.5, without installing the external websocket-client package or any other 3rd party Python package.

I have searched the Internet and those examples of code using Python socket module I've seen, refer to connections via http or tcp whereas I need to establish connection via wss.

Upvotes: 3

Views: 5181

Answers (1)

g.o.a.t.
g.o.a.t.

Reputation: 438

Very late, but for anyone who might stumble here...Web Sockets protocol is built on TCP so it is expected that implementations of the protocol establish connections via TCP. Also, Web Socket's opening handshake is done following HTTP. This would also explain why Alex saw HTTP connections. If you want to see how to implement one from scratch, install web socket modules (autobahn, which in turn would lead to installing and reading Twisted and asyncio modules, or wampy) and dive into the code. Would recommend reading the Web Sockets protocol specifications at https://www.rfc-editor.org/rfc/rfc6455 before tackling the modules.

Upvotes: 2

Related Questions