python之socket模块

时间:2023-01-11 15:44:31

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三次握手

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAnMAAACUCAIAAAB3DDhKAAAWL0lEQVR4nO2dzbGsOBJGy5yxAYOIaDfGAjyYXrQNPDPaAFazeqtZtQHMgirQT2ZKAkEJ7jkxET2vhKTUz9WHUkJ6/fnnn3/88ccrj26Y5oWxl8L7UQ26KTVK1A3TPA1dJYuOYpUo1b7H2FI/Lw8793ZaAQAeTZGyAgAAQIIGlXWZ2zxq6luZ5/kGAAAeBMp6Q1BWAICGaVBZ26MbpqaU7LiytlYiAIAHgbJm0JoOoawAAA0TKms/Wjsoj4Sm8LeO+gm9N3b24xrk/N9NaZwkQtVYnhcT32Qm3hvrRdPi64TRw4iWVUJ0zyqnhO/nvDJ71Rk/u7dEAACQQpizeqIVcSQ0k36Ul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PP31Hqn6cZ5+xcpanMMnl0AYnFuBs5RVJlHP0uPBnCYaPSUntDzTzzUw/eLl1ECGsq7PJ/9a/Ny/NWcV3xSrKas3pct6cchBdp1qPda23u7McZ+chmHcXDzjsA0xed5gY8660zcOEbayKuPD+2XKHjiK43Zd2KhXrLOGWQUvm9Gb6DSVzFkVXV0TDl8SP1Vg9+lQ+yWbstpITtkYEbphnoblx3Gcx76PlDUh80rBAmEIjM9RVjVfq567YYzT0J0Bur9Ce3fS2tfPQX5/XH/+OAcLlFWZDZWV1883bbWB3YK+HUrPTQ/zukD5vtOwIOGyQt9n/M0EzSvNUbUS2a2QaiM/46iy7NHMbDmr10EpgrJ6ywNivRrqWCuu5JeIKZ2naf3KS17+6/sEGUOhKBimiVGxvG5t9Gkn4tjrTqBdM1mrMrohaoMyZQ2XkN9ljNTJnAG8SpQ1KpKTbfS7rsxCp3QeMMcqK76qBkILlyir/G6aUV6nuIvT8QpvsJftZxkxMk/sOWqKscH2iGR2ArVEm03im4BYIjvDpDl+wwrNbP8Bmy2n9joohRP5C5F7mzgCGRPWL+GPTSHyWJU71PxYDGVNc9rgVceTl5lKab9qn2SJ8JSCCcqawPcNhbPD7R1P3Gv1CEmqtoz7UPxBuLiejC500KYK4z76oUHNgAnKmiB0zvDHBO2y9dY6/RT90KBmwKQVZf3Pv6z/AQAA3AWUFQAAoCYoKwAAQEX+Dw44WW/Lq54FAAAAAElFTkSuQmCC" alt="" />

http://www.open-open.com/lib/view/open1342570701932.html

http://www.cnblogs.com/GarfieldTom/archive/2012/12/16/2820143.html