[英]BrokenPipeError: [Errno 32] Broken pipe for makefile socket?
[英]conn.send('Hi'.encode()) BrokenPipeError: [Errno 32] Broken pipe (SOCKET)
嗨,我制作了工作正常的模型服務器客戶端,我還創建了單獨的 GUI,它需要兩個輸入server IP and port
,它只檢查server
是否啟動。 但是當我運行服務器然后運行我的 GUI 並輸入服務器 IP 和端口時,它在 GUI 上顯示已connected
,但在服務器端它會拋出此錯誤。 服務器客戶端工作正常,但 GUI 與服務器的集成在服務器端引發以下錯誤。
conn.send('Hi'.encode()) # send only takes string BrokenPipeError: [Errno 32] Broken pip
這是服務器代碼:
from socket import *
# Importing all from thread
import threading
# Defining server address and port
host = 'localhost'
port = 52000
data = " "
# Creating socket object
sock = socket()
# Binding socket to a address. bind() takes tuple of host and port.
sock.bind((host, port))
# Listening at the address
sock.listen(5) # 5 denotes the number of clients can queue
def clientthread(conn):
# infinite loop so that function do not terminate and thread do not end.
while True:
# Sending message to connected client
conn.send('Hi'.encode('utf-8')) # send only takes string
data =conn.recv(1024)
print (data.decode())
while True:
# Accepting incoming connections
conn, addr = sock.accept()
# Creating new thread. Calling clientthread function for this function and passing conn as argument.
thread = threading.Thread(target=clientthread, args=(conn,))
thread.start()
conn.close()
sock.close()
這是導致問題的 Gui 代碼的一部分:
def isOpen(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, int(port)))
data=s.recv(1024)
if data== b'Hi':
print("connected")
return True
except:
print("not connected")
return False
def check_password(self):
self.isOpen('localhost', 52000)
你的問題很簡單。
由於連接已被客戶端關閉,服務器無法在循環內發送或接收下一條消息,因為它是無限的。 這就是錯誤的原因! 在關閉連接的情況下也沒有錯誤處理,也沒有在每一端關閉的協議。
如果您需要一個函數來檢查服務器是否在線,您應該創建一個函數,(但我確信一個簡單的連接就足夠了),它的工作方式類似於 ping。 例子:
客戶端功能:
def isOpen(self, ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((str(ip), int(port)))
s.send("ping".encode('utf-8'))
return s.recv(1024).decode('utf-8') == "pong" # return whether the response match or not
except:
return False # cant connect
服務器功能:
def clientthread(conn):
while True:
msg = conn.recv(1024).decode('utf-8') #receiving a message
if msg == "ping":
conn.send("pong".encode('utf-8')) # sending the response
conn.close() # closing the connection on both sides
break # since we only need to check whether the server is online, we break
從您之前的問題中,我可以告訴您在理解 TCP套接字通信的工作原理方面存在一些問題。 請花點時間閱讀一些關於如何通過套接字進行通信的文章。 如果您不需要實時通信(連續數據流,如視頻、游戲服務器等),只需登錄表單,請堅持使用眾所周知的協議,如 HTTP。 如果您剛開始接觸套接字編程,創建自己的可靠協議可能會有點復雜。
您可以將燒瓶用於 HTTP 后端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.