pygame python3.5_Python3.5通过套接字发送对象(Pygame cam图像)

我做了一个用当前时间发送曲面的例子。在

(Pygame无法使用我的相机)。在

它使用struc.pack()在发送图像之前发送图像大小始终为4字节。所以客户机首先接收4个字节并具有图像大小。然后它就可以利用这些信息来接收图像。在

两者都使用循环发送/接收所有时间。在

服务器.py#!/usr/bin/env python

import pygame

from threading import Thread

import socket

import struct # to send `int` as `4 bytes`

import time # for test

# - constants -

ADDRESS = ("localhost", 12801)

SURFACE_SIZE = (640, 480)

WHITE = (255, 255, 255)

BLACK = ( 0, 0, 0)

GREEN = ( 0, 255, 0)

# - classes -

class Streaming(Thread):

def __init__(self):

Thread.__init__(self)

pygame.init()

#pygame.camera.init()

#self.cam = pygame.camera.Camera("/dev/video0", SURFACE_SIZE)

#self.cam.start()

# create surface to imitate camera image

self.image = pygame.Surface(SURFACE_SIZE)

self.image_rect = self.image.get_rect()

# create font to display text on surface

self.font = pygame.font.Font(None, 50)

def get_image(self):

# emulate cam.get_image()

# get current time as string

current_time = time.strftime('%H:%M:%S.%s')

# render surface with text (and center it)

text = self.font.render(current_time, True, BLACK, GREEN)

text_rect = text.get_rect(center=self.image_rect.center)

# clear image and put new text

self.image.fill(WHITE)

self.image.blit(text, text_rect)

return self.image

def run(self):

s = socket.socket()

# solution for: "socket.error: [Errno 98] Address already in use"

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind(ADDRESS)

s.listen(1)

print("Wait for connection")

try:

sc, info = s.accept()

print("Video client connected:", info)

while True:

# get image surface

#image = self.cam.get_image()

image = self.get_image()

# convert surface to string

img_str = pygame.image.tostring(image, 'RGB')

print('len:', len(img_str))

# send string size

len_str = struct.pack('!i', len(img_str))

sc.send(len_str)

# send string image

sc.send(img_str)

# wait

time.sleep(0.5)

except Exception as e:

print(e)

finally:

# exit

print("Closing socket and exit")

sc.close()

s.close()

pygame.quit()

# - main -

Streaming().run()

客户端.py

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值