`
f002489
  • 浏览: 264304 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

python实现socket通讯(UDP)

阅读更多

http://www.91linux.com/html/article/program/python/20090316/16108.html

http://www.91linux.com/html/article/program/python/list_33_6.html

 

UDP协议相比TCP要简单许多,虽然数据无法保证完整性.
先看一下client端的演示代码:

import socket
s = socket. socket( socket. AF_INET, socket. SOCK_DGRAM)
port = 8000
host = '192.168.1.102'
while True:
    msg = raw_input( )
    if not msg:
        break
    s. sendto( msg, ( host, port) )
s. close( )

注意,在创建socket的时候,第二个参数要为SOCK_DGRAM,然后,我们只需要调用sendto即可以了,真是太方便了.
再看看server端代码:

import socket
s = socket. socket( socket. AF_INET, socket. SOCK_DGRAM)
s. bind( ( '192.168.1.102' , 8000) )
while True:
        data, addr = s. recvfrom( 1024)
        if not data:
                print 'client has exited!'
                break
        print 'received:' , data, 'from' , addr
s. close( )

创建socket后,然后bind至IP及端口.下一步在循环中接受数据.recvfrom的返回值包括两个,data是接受到的数据,addr是连接的client端的地址.真是太方便了.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics