python socket 学习

时间:2023-03-08 22:23:21

Python在网络通讯方面功能强大,今天学习一下Socket通讯的基本方式,分别是UDP通讯和TCP通讯。

UDP通讯

upd 服务端

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import socket ADDR,PORT = 'localhost',7878
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sock.bind((ADDR,PORT)) print 'waiting for connection...' while True:
data, addr = sock.recvfrom(1024)
print('Received data:', data, 'from', addr)

upd客户端

 #!/usr/bin/env python
# -*- coding:utf-8 -*- import socket ADDR,PORT = 'localhost',7878
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
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服务端

 #!/usr/bin/env python
# -*- coding:utf-8 -*- from socket import *
import os ADDR,PORT = 'localhost',7878
sock = socket(AF_INET,SOCK_STREAM)
sock.bind((ADDR,PORT))
sock.listen(5) while True:
conn,addr = sock.accept()
print "new conn:",addr
while True:
print 'waiting for connection'
data = conn.recv(1024)
if not data:
print '客户端已经断开'
break
print '执行指令',data
cmd_res = os.popen(data).read() #为执行传回的指令
if len(cmd_res) == 0:
print 'cmd has no output...' conn.send(str(len(cmd_res)).encode('utf-8')) #发送大小
#client_chk = conn.recv(1024) 解决粘包问题 #wait client to confirm
conn.send(cmd_res)
print 'send done'
conn.close()
sock.close()

TCP客户端

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
from socket import * ADDR,PORT = 'localhost',7878
sock = socket(AF_INET,SOCK_STREAM)
sock.connect((ADDR,PORT))
while True:
data = raw_input('>>')
sock.send(data)
print('发送信息到%s:%s' % (host, data))
cmd_size = sock.recv(1024)
print '命令结果大小 size',cmd_size
sock.send('准备好接收了,可以发了')
received_size = 0
received_data = b''
while received_size < int(cmd_size):
data = sock.recv(1024)
received_size += len(data)
received_data += data
print received_size
else:
print '=================\r\n'
print 'cmd receive done',received_size
print 'receive data:\r\n',received_data sock.close()