簡體   English   中英

Python套接字腳本<-> HTML客戶端

[英]Python Socket script <-> HTML client

使用以下代碼,我可以在Raspberry Pi中創建一個Socket Server,如果通過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> 

如您所見,所有工作正常:-多個客戶端可以連接-從android應用程序連接的客戶端可以發送和接收消息並保持連接打開-接受html客戶端,但不發送消息

在此處輸入圖片說明

這不是您使用Python創建的Websocket應用程序,而是Socket應用程序。 Websocket是位於HTTP之上的協議,位於HTTP之上,而TCP則是您在Python應用程序中使用的實際套接字。 要使用python創建Websockets服務器,您可以嘗試使用websockets庫。

有關差異的更多詳細信息,請參見套接字和websocket之間的差異 TCP套接字和Web套接字之間的差異,又需要花費更多時間 有關服務器代碼,請參見https://stackoverflow.com/questions/5839054/websocket-server-in-python

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM