请教如何使用python的socket发送二进制数据
2个回答
展开全部
客户端clt.py
# coding: utf8
import socket
HOST = '192.168.1.101'
PORT = 12008
def send_data(data):
try:
sock_clt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_clt.connect((HOST, PORT))
sock_clt.send(data)
finally:
sock_clt.close()
while True:
send_data('你的二进制数据')
服务端svr.py
# coding: utf8
import socket
HOST = ''
PORT = 12008
SIZE = 4096
sock_svr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# python socket server重启后,端口被占用的解决方法
sock_svr.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
sock_svr.bind((HOST, PORT))
sock_svr.listen(1)
while True:
print "waiting of the client to connect"
clt_conn_sock, addr = sock_svr.accept()
print 'Connected by', addr
comp_data = ''
while True:
data = clt_conn_sock.recv(SIZE)
if not data:
break
comp_data += data
clt_conn_sock.close()
if not comp_data:
continue
print comp_data
服务端可以使用socket的select或poll,也可以使用twisted
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询