大家好,我有这个 python 代码,它可以将实时视频从客户端发送到服务器,它运行良好,直到我添加了服务器在接收实时源时向客户端发送“hello”的行,它停止工作. 客户端使用多线程,一种用于接收,一种用于发送实时提要。 有什么关于如何解决这个问题的帮助吗?。
这是我的服务器代码:
import socket, cv2, pickle, struct
import threading
import pyshine as ps
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname()
host_ip = socket.gethostbyname(host_name)
print('HOST IP:', host_ip)
port = 9999
socket_address = (host_ip, port)
print("Listening at", socket_address)
i=0
def show_client(addr, client_socket):
try:
print('CLIENT {} CONNECTED!'.format(addr))
if client_socket: # if a client socket exists
data = b""
payload_size = struct.calcsize("Q")
while True:
while len(data) < payload_size:
packet = client_socket.recv(4 * 1024) # 4K
if not packet: break
data += packet
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("Q", packed_msg_size)[0]
while len(data) < msg_size:
data += client_socket.recv(4 * 1024)
frame_data = data[:msg_size]
data = data[msg_size:]
frame = pickle.loads(frame_data)
text = f"CLIENT: {addr}"
frame = ps.putBText(frame, text, 10, 10, vspace=10, hspace=1, font_scale=0.7,
background_RGB=(255, 0, 0), text_RGB=(255, 250, 250))
cv2.imshow(f"FROM {addr}", frame)
client_socket.sendall('hello') # send back to client
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
client_socket.close()
except Exception as e:
print(f"CLINET {addr} DISCONNECTED")
pass
server_socket.bind(socket_address)
server_socket.listen()
while True:
client_socket, addr = server_socket.accept()
thread = threading.Thread(target=show_client, args=(addr, client_socket))
thread.start()
print("TOTAL CLIENTS ", threading.activeCount() - 1)
这是我的客户端代码:
import socket,cv2, pickle,struct
import imutils # pip install imutils
import threading
import sys
camera = True
if camera == True:
vid = cv2.VideoCapture(0)
else:
vid = cv2.VideoCapture('resources/video3.mp4')
client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host_ip = '192.168.100.22' # Here according to your server ip write the address
i=1
port = 9999
client_socket.connect((host_ip,port))
def sendvid():
while True:
try:
if client_socket:
while True:
try:
img, frame = vid.read()
frame = imutils.resize(frame,width=380)
a = pickle.dumps(frame)
message = struct.pack("Q",len(a))+a
client_socket.sendall(message)
#print(client_socket.recv(16))
cv2.imshow(f"TO: {host_ip}",frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
client_socket.close()
except:
print('VIDEO FINISHED!')
break
def recv():
while True:
print('client_socket.recv(16)')
print(client_socket.recv(16))
thread1 = threading.Thread(target=sendvid)
thread1.start()
print("hello")
thread2 = threading.Thread(target=recv)
thread2.start()