套接字编程 - 不断发送和接收数据(python)

时间:2015-02-19 14:40:53

标签: python sockets

我正在编写一个非常简单的屏幕共享程序。 我有发送和恢复屏幕图片的代码。我希望服务器能够随时重新接收数据,我希望客户端每隔3秒发送一次数据。这是代码:

服务器:

import socket
import zlib

def conv(code):
    with open('Image2.pgm', 'wb') as f:
        f.write(code)

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 100000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    str = zlib.decompress(data) 
    conv(str)
    print "All OK"
    conn.send(data)  # echo
conn.close()

客户端:

import socket
import pyscreenshot as ImageGrab
import zlib

def PrtSc():
    ImageGrab.grab_to_file("Image.pgm")
    f = open("Image.pgm", "rb")
    Image = f.read()
    Image = zlib.compress(Image)
    return Image

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 100000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(PrtSc())
data = s.recv(BUFFER_SIZE)
s.close()

print "received data:", data

谢谢:)

0 个答案:

没有答案