1. python-client端数据编写
-----------------------------------------------------
#!/usr/bin/python
import time
import socket
import json
import random
HOST='192.168.2.22'
PORT=8008
BUFFER=4096
soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.connect((HOST,PORT))
while 1:
time.sleep(0.1)
m0=random.randint(0,25)
m1=random.randint(0,25)
m2=random.randint(0,25)
m3=random.randint(0,55)
m4=random.randint(0,55)
m5=random.randint(0,55)
m6=random.randint(0,255)
m7=random.randint(0,255)
m8=random.randint(0,255)
m9=random.randint(0,255)
mess=[m0,m1,m2,m3,m4,m5,m6,m7,m8,m9]
#soc.send(json.dumps(mess))
soc.send(str(mess))
buf=soc.recv(BUFFER)
print(buf)
soc.close()
2. python-server端程序编写
#!/usr/bin/python3
import socket
import json
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.2.22',8008))
s.listen(5)
print('Waiting for connection...')
sock, addr = s.accept()
while 1:
sock.settimeout(5)
recvdata=sock.recv(4096)
#if语句判断是否有数据或者数据是否有中断
#防止出现json-nodata错误,导致server程序中断
if len(recvdata) !=0:
buf=json.loads(recvdata)
print(buf)
sock.send('yes i recv')
else:
print('pass')
sock.send('out off client')
#数据中断时进行服务重启程序,先close 再accept等待重新连线
#可以防止出现当client意外终止导致server的中断(Broken pipe错误)
sock.close()
sock, addr = s.accept()
#sock.send('yes')
sock.close()
3. 程序运行
python clien.py
python server.p
网友评论