【问题标题】:Python Socket script <-> HTML clientPython Socket 脚本 <-> HTML 客户端
【发布时间】:2016-03-10 07:32:40
【问题描述】:

使用以下代码,我可以在我的 Raspberry Pi 中创建一个 Socket 服务器,如果通过 Socket 客户端(如 Android 应用程序)进行访问,它会非常有用。

但是,我想将 websocket 功能集成到我的网站中,所以我开始尝试通过 HTML 文本框发送一条简单的消息,python 脚本将接收并回复。

问题是我无法让 HTML 代码打开、发送和保持打开套接字以进行通信。我确实承认连接到 python 的 html 客户端但无法获取数据,因为它似乎连接关闭。

Python 代码

#!/usr/bin/env python

#python3
# https://pythonprogramming.net/client-server-python-sockets/

import socket               # Websocket 
import sys                  # 
from _thread import *       # Used for multi-threading      The thread module has been renamed to _thread in Python 3.
import time                 # Used to create delays

# ******* WEBSOCKET VARIABLES *******
numberClients = 0
host = ''
PORT = 2223
# ******* WEBSOCKET VARIABLES *******

# ************************** FUNCTIONS **************************
def threaded_client(conn,address):      # receive as parameters, the connection object (conn), and the address object that contains the ip and port
    global numberClients
    conn.send(str.encode('Welcome, type your info\n'))  # data should be bytes
    numberClients = numberClients + 1

    #           CHECK USER USING PASSWORD OR SOMETHING
    if ("192.168" in str(address[0])):
        print ("     VALID CLIENT!!")

        while True:
            data = conn.recv(2048)
            if (data):
                reply = "" + 'Server output: '+ data.decode('utf-8').rstrip() + "\n"
                print(str(address[0]) + " - Clients(" + str(numberClients) + ") -> Data received: >" + data.decode('utf-8').rstrip() + "<")
            if not data:
                #print("no data")
                #break
                foo = 2
            try:
                conn.sendall(str.encode(reply))     # data should be bytes
            except Exception as e:
                foo = 1
        print("Thread connection closed by client: " + address[0])
        conn.close()
        numberClients = numberClients - 1

    else:
        print ("     INVALID CLIENT -> Thread connection closed by USER VALIDATION: " + address[0])
        conn.close()
        numberClients = numberClients - 1
# ************************** FUNCTIONS **************************




# ************************** SETUP **************************
print ("\n----------- Starting Websocket Python Program -----------\n")

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   # "s" here is being returned a "socket descriptor" by socket.socket.
print(s)

# we are simply attempeting to bind a socket locally, on PORT 5555.
try:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)         # reuse the port number (in case we just got an error and port was not freed)
    s.bind((host, PORT))                # server side - take IN connections
    print ("Server started on port " + str(PORT))
except socket.error as e:
    print(str(e))
    print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    #sys.exit()
print('Socket bind complete')

s.listen(5)     # the "5" stands for how many incoming connections we're willing to queue before denying any more.

print('Waiting for a connection.')
# ************************** SETUP **************************



# ************************** MAIN LOOP **************************
while True:
    conn, addr = s.accept()         # code will stop here whilst waiting for a new connection. Old connections will be running in the threads
    print('Connected to: '+addr[0]+':'+str(addr[1]))

    start_new_thread(threaded_client,(conn,addr))   
# ************************** MAIN LOOP **************************

我尝试过的众多 HTML 代码之一:

  <script type="text/javascript">
     function WebSocketTest()
     {
        if ("WebSocket" in window)
        {
           alert("WebSocket is supported by your Browser!");

           // Let us open a web socket
           var ws = new WebSocket("ws://192.168.1.20:5252/echo");
           ws.onopen = function()
           {
              // Web Socket is connected, send data using send()
              ws.send("133:L1");
              alert("Message is sent...");
           };

           ws.onmessage = function (evt) 
           { 
              var received_msg = evt.data;
              alert("Message is received...");
           };

           ws.onclose = function()
           { 
              // websocket is closed.
              alert("Connection is closed..."); 
           };
        }

        else
        {
           // The browser doesn't support WebSocket
           alert("WebSocket NOT supported by your Browser!");
        }
     }
  </script>
      </head>    <body>

  <div id="sse">
     <a href="javascript:WebSocketTest()">Run WebSocket</a>
  </div>
      </body> </html>

正如您所看到的那样: - 多个客户端可以连接 - 从安卓应用程序连接的客户端可以发送和接收消息并保持连接打开 - 接受 html 客户端,但未发送任何消息

【问题讨论】:

    标签: javascript python html sockets websocket


    【解决方案1】:

    这不是你用 Python 创建的 Websocket 应用程序,而是一个 Socket 应用程序。 Websocket 是 HTTP 之上的协议,它位于 TCP 之上,TCP 是您在 Python 应用程序中使用的实际套接字。要使用 python 创建 Websockets 服务器,您可以尝试 websockets 库。

    有关差异的更多详细信息,请参阅 Difference between socket and websocket?Differences between TCP sockets and web sockets, one more time 了解差异。服务器代码见https://stackoverflow.com/questions/5839054/websocket-server-in-python

    【讨论】:

    • 哇!我这边犯了大错。我想保留python“socket”脚本,因为它已经很好用了。是否可以创建一个 html 套接字客户端?我的第二个目标是创建一个与 python 套接字通信的 Android 应用程序。
    • @Serge:HTML 中没有普通套接字的标准接口。对于 Chrome,请查看 sockets_tcp
    • 所以考虑到我的目标:让 python 脚本为 Android 应用程序和 HTML 网站提供实时快速信息。我应该修改我的 python 脚本以使用 WebSocket 而不是 Sockets?
    • @Serge:如果你想支持所有(最近的)浏览器,那么你必须使用 WebSockets。浏览器支持见caniuse
    • 是否也可以通过 Android 应用程序进行通信?现在非常好,我可以使用任何 android 应用程序客户端连接到它。我希望能够继续这样做,但也可以访问 html。
    猜你喜欢
    • 2018-08-23
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2011-09-09
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多