UU Blog

Python简单的socket通讯例子

公司有块业务是靠socket提供端口供给业务查询的。

之前每次测试socket发送数据都略麻烦,所以自己用python搞了一次。

根据业务之前的逻辑,检测字段包含EOF结束读取。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import socket
#import codecs

#encoder = codecs.getencoder("utf-8")
senddata = '{"action":"compute","device":"ios","map":"0","start":"2017-05-19","day":"25","type":"17","orientation":"0","order_total_id":"950","store_id":"12"}EOF\n'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('dev.xxxx.net', 31))
s.send(senddata)

buffer = []
while True:
d = s.recv(65535)
if d:
buffer.append(d)
else:
break
if 'EOF' in d[-5:-1]:
break
# while True:
# d = s.recv(1024)
# if d:
# buffer.append(d)
# else:
# break
data = ''.join(buffer)
print data
s.close()
给作者打一针鸡血