好记性不如铅笔头

python && jython, 编程

【转】Python的TCP/UDP通讯

本文转自【 http://www.cnblogs.com/codeio/archive/2011/08/31/2160408.html 】

[Python]Socket的TCP/UDP应用

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 – 指明所要接收的协议包。

UDP小实例

server.py

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()

client.py

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,运行结果:

TCP小例子

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,运行结果:

Leave a Reply

14 + 18 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据