Python在网络通讯方面功能强大,今天学习一下Socket通讯的基本方式,分别是UDP通讯和TCP通讯。
UDP通讯
upd 服务端
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import socket 5 6 ADDR,PORT = 'localhost',7878 7 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 8 sock.bind((ADDR,PORT)) 9 10 print 'waiting for connection...'11 12 while True:13 data, addr = sock.recvfrom(1024)14 print('Received data:', data, 'from', addr)
upd客户端
1 #!/usr/bin/env python2 # -*- coding:utf-8 -*-3 4 import socket5 6 ADDR,PORT = 'localhost',78787 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)8 sock.sendto(b'hello,this is a test info !',(ADDR,PORT))
先开启server端,等待client端的接入,每请求一次client会打印如下内容
waiting for connection...
('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 57331))('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 61396))('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 61261))('Received data:', 'hello,this is a test info !', 'from', ('127.0.0.1', 54875))TCP通讯
TCP服务端
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from socket import * 5 import os 6 7 ADDR,PORT = 'localhost',7878 8 sock = socket(AF_INET,SOCK_STREAM) 9 sock.bind((ADDR,PORT))10 sock.listen(5)11 12 while True:13 conn,addr = sock.accept()14 print "new conn:",addr15 while True:16 print 'waiting for connection'17 data = conn.recv(1024)18 if not data:19 print '客户端已经断开'20 break21 print '执行指令',data22 cmd_res = os.popen(data).read() #为执行传回的指令23 if len(cmd_res) == 0:24 print 'cmd has no output...'25 26 conn.send(str(len(cmd_res)).encode('utf-8')) #发送大小27 #client_chk = conn.recv(1024) 解决粘包问题 #wait client to confirm28 conn.send(cmd_res)29 print 'send done'30 conn.close()31 sock.close()
TCP客户端
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from socket import * 4 5 ADDR,PORT = 'localhost',7878 6 sock = socket(AF_INET,SOCK_STREAM) 7 sock.connect((ADDR,PORT)) 8 while True: 9 data = raw_input('>>')10 sock.send(data)11 print('发送信息到%s:%s' % (host, data))12 cmd_size = sock.recv(1024)13 print '命令结果大小 size',cmd_size14 sock.send('准备好接收了,可以发了')15 received_size = 016 received_data = b''17 while received_size < int(cmd_size):18 data = sock.recv(1024)19 received_size += len(data)20 received_data += data21 print received_size22 else:23 print '=================\r\n'24 print 'cmd receive done',received_size25 print 'receive data:\r\n',received_data26 27 sock.close()