我正在使用Python从互联网上获得的网络摄像头脚本,并且正在使用pygame模块,问题是我的网络摄像头将打开,然后连接断开,并表示套接字已准备好使用,服务器代码是
import socket
import pygame
import sys
port=5014
#create pygame screen
screen = pygame.display.set_mode((800,600),0)
while True:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",port)) # server is available on the whole network by setting host to ""
s.listen(1)
connection, addr = s.accept()
received = []
# loop .recv, it returns empty string when done, then transmitted data is completely received
while True:
recvd_data = connection.recv(1440021)
if not recvd_data:
break
else:
received.append(recvd_data)
dataset = ''.join(received)
image = pygame.image.fromstring(dataset,(800,600),"RGB") # convert received image from string
#image = pygame.transform.scale(image,(800,600)) # scale image to 800*600
screen.blit(image,(0,0)) # "show image" on the screen
pygame.display.update()
# check for quit events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
客户端代码是
import socket
import pygame
import pygame.camera
import sys
import time
host = "localhost"
port = 5014
pygame.init()
pygame.camera.init()
cam_list = pygame.camera.list_cameras() # list available cameras
webcam = pygame.camera.Camera(cam_list[0],(800,600)) # use first camera in list and set resolution
webcam.start() # start camera
while True:
image = webcam.get_image() # capture image
data = pygame.image.tostring(image,"RGB") # convert captured image to string, use RGB color scheme
#print sys.getsizeof(data) # in case somebody wants to know the size of the captured image
# prepare for connection to server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP is used
s.connect((host, port))
s.sendall(data)
s.close()
time.sleep(0.1)
我在服务器上收到的错误是
Traceback (most recent call last):
File "/root/Desktop/s.py", line 20, in <module>
s.bind(("",port)) # server is available on the whole network by setting host to ""
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in us
我在客户端收到的错误是
Traceback (most recent call last):
File "/root/Desktop/c.py", line 45, in <module>
s.connect((host, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
是的,我已经更改了端口号,有人知道出了什么问题吗?
最佳答案
在服务器中,您应该只创建一次套接字(在 while 之外),然后接受
多个连接(在 while 内)。
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",port)) # server is available on the whole network by setting host to ""
s.listen(1)
while True:
connection, addr = s.accept()
received = []
...
关于python - 使用 pygame 在 python 中通过套接字进行流式传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22922577/