import socket host = '127.0.0.1' port = 9999 #创建一个tcp socket套接字 tcp_server = socket.socket(socket.AF_INIT, socket.SOCK.STREAM) #绑定ip,port tcp_server.bind((host, port)) #设置最大连接数 tcp_server.listen(5) #监听 while True: client, address = tcp_server.accept() print "received from %s:%d" %(address[0], address[1]) #设置接收字节 request = client.recv(1024) print 'receive data %s' %request #发送接收成功通知 client.send('ACK!') #关闭 client.close()
一个简单的tcp服务端
import socket target_host = '127.0.0.1' target_port = 9999 #创建一个tcp socket套接字 tcp_client = socket.socket(socket.AF_INIT, socket.SOCK_STREAM) #连接到目标 tcp_client.connect((target_host, target_port)) #发送数据 tcp_client.send('test') #接收来自服务器的数据 response = tcp_client.recv(1024) print response tcp_client.close
一个简单的tcp客户端
import socket host = '127.0.0.1' port = 9999 udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_server.bind((host, port)) print '..waiting for message..' while True: data, address = udp_server.recvfrom(1024) print 'Received data %s for %s:%d' %(data, address[0], address[1]) udp_server.sendto('success', address) udp_server.close()
一个简单的UDP服务端
import socket target_host = '127.0.0.1' target_port = 9999 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto("AAABBBCCC", (target_host, target_port)) data, addr = client.recvfrom(4096) print data print addr
client.close()
一个简单的UDP客户端
最大的区别在于是否需要建立连接,tcp是可靠的需要连接,而udp是不可靠的不需要连接,其他的都比较类似