码迷,mamicode.com
首页 > 编程语言 > 详细

python之socket模块

时间:2014-07-22 23:17:33      阅读:507      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   os   

UDP

client

mamicode.com,码迷
#!/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))
mamicode.com,码迷

server

mamicode.com,码迷
#!/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)
mamicode.com,码迷

TCP

client

mamicode.com,码迷
#!/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
mamicode.com,码迷

server

mamicode.com,码迷
#!/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()
mamicode.com,码迷

 

测试连接MySQL端口,完成tcp三次握手

mamicode.com,码迷

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

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

python之socket模块,码迷,mamicode.com

python之socket模块

标签:style   blog   http   java   color   os   

原文地址:http://www.cnblogs.com/gsblog/p/3699645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!