首页 > 代码库 > python之socket模块
python之socket模块
UDP
client
#!/usr/bin/env python2.7 #-*-coding:utf-8 -*- import socket s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.sendto("hello",("localhost",8001)) data,addr = s.recvfrom(1024) print "receive data:%s from %s" % (data,str(addr))
server
#!/usr/bin/env python2.7 #-*-coding:utf-8 -*- import socket port=8001 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(("",port)) while True: data,client = s.recvfrom(1024) print "receive a connection from %s" % str(client) s.sendto("echo:"+data,client)
TCP
client
#!/usr/bin/env python2.7 #-*-coding:utf-8 -*- import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host="localhost" port=5531 s.connect((host,port)) msg=raw_input("Msg:") s.send(msg) data=s.recv(1024) print "Reply from server----%s" % data
server
#!/usr/bin/env python2.7 #-*-coding:utf-8-*- import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host = "localhost" port = 1235 s.bind((host,port)) s.listen(3) while True: client,ipaddr = s.accept() print "Got a connect from %s" % str(ipaddr) data = client.recv(1024) print "receive data:%s" % data client.send("echo:"+data) client.close()
测试连接MySQL端口,完成tcp三次握手
http://www.open-open.com/lib/view/open1342570701932.html
http://www.cnblogs.com/GarfieldTom/archive/2012/12/16/2820143.html
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。