问题
I tried to search in the internet for this subject, But I didn't found some answers.
If some know how can I use a browser as a client in python sockets it will be very good.
回答1:
To use the browser as a client to a python (server) socket, you simply need to point it to the right endpoint.
Assuming you are running the browser and the python server on the same machine, and that you're opening port 1234 on the server socket, you simply need to open the localhost:1234
URL in your browser.
Of course, what happens next is entirely dependent on how you handle the communication in your program. Most browsers will understand plain text put directly on the socket, but you probably want to talk HTTP.
It's worth mentioning that using a plain socket
to communicate with a browser is, at best, uncommon. There may be better solutions, depending on what, exactly, you want to do:
- If you just want to quickly serve a few files from a directory (i.e.: often called a "directory listing"), you can use SimpleHTTPServer
- If you're trying to build a website, you should look into a web framework, such as Django, Flask or CherryPy
- If you want a lower-level highly asynchronous scalable communication, Tornado is a popular choice
回答2:
You might want to consider using websockets. They essentially function like regular TCP sockets, but are initiated with a HTTP handshake, making them suitable for browsers. They are supported in recent versions of all major browsers. There are many libraries available that adapt common python webservers to serve websockets as well, for example:
https://pypi.python.org/pypi/gevent-websocket/
if you like gevent.
They also support an SSL layer, which is called using a url starting with "wss://" on the browser side. More information here:
https://www.websocket.org/
来源:https://stackoverflow.com/questions/25741177/how-do-i-use-a-browser-as-a-client-in-python-sockets