Socket是应用层与TCP/IP协议簇通信的中间层,可以看作提供给应用层所用的接口。
Python中,主要用socket.socket([family[, type[, proto]]])方法来创建一个socket实例,相关参数说明:
family - 套接字地址结构,有AF_INET、AF_INET6和AF_UNIX。
type - 数据传输的类型,广泛使用的有SOCK_STREAM(数据流)和SOCK_DGRAM(数据报文),SOCK_STREAM是面向连接的,SOCK_DGRAM是无连接的,如ATM和TCP协议属于SOCK_STREAM类型,而IRDA和UDP协议属于SOCK_DGRAM类型。
proto - 指明所要接收的协议包。
import socket server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) server.bind(("127.0.0.1",17800)) print("udp server start") while True: data,addr = server.recvfrom(1024) text = str(data, encoding = "utf-8") print("address:%s data:%s"%(addr,text)) if text == "quit": break print("udp server finish") server.close()
import socket client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print("udp client start") while True: data = input("please input content:") client.sendto(bytes(data,"utf-8"),("127.0.0.1", 17800)) if data == "quit": break print("udp client finish") client.close()
先运行server.py,再运行client.py,运行结果:
server.py代码
import socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("127.0.0.1",17800)) server.listen(5) print("tcp server start") while True: conn,addr = server.accept() print("client connect, address: ",addr) conn.send(b"welcome to server") data = conn.recv(1024) print(str(data,encoding="utf-8")) conn.close() print("tcp server finish") server.close()
client.py代码
import socket print("udp client1 start") client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client1.connect(("127.0.0.1",17800)) data1 = client1.recv(1024) print(str(data1,encoding="utf-8")) client1.send(b'I am client1') client1.close() print("udp client1 finish") print("udp client2 start") client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client2.connect(("127.0.0.1",17800)) data2 = client2.recv(1024) print(str(data2,encoding="utf-8")) client2.send(b'I am client2') client2.close() print("udp client2 finish")
先运行server.py,再运行client.py,运行结果:
本人一直都是做B/S方面的,对socket通信方面的认识还很肤浅,只停留在如何应用的层次,以后还需要多多研究和努力。这里有几个心得:
- 使用UDP数据报文套接方式,系统会自动分配端口号,客户机不需要调用bind()函数显示指定,而是用UNIX域数据报套接字就必须调用bind()函数来显示指定路径名
- Python文档中已经有若干个socket通信的例子,包括IPV4、IPV6下的TCP通信,大家可以去看看。在Doc文件夹下面的chm帮助文档真是好东西,E文好的朋友,可以多去看看。