您的位置:首页 > 编程语言 > Python开发

Python的Socket模块TCP UDP简单使用

2014-06-23 15:30 1016 查看
1、使用socket模块编写UDP服务端,代码如下。从中需要注意的知识是:bind()和connect()函数都只有一个参数,参数是表示地址的元组(hostname,port),千万不要写成两个参数了。

#! /usr/bin/env python
#coding=utf-8
#使用socket模块编写的服务器(通过UDP传输数据)
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("",10000))  #bind函数只有一个参数
while True:
data,client=s.recvfrom(1024)
print "receive a connection from %s"  %str(client)   #str()函数可以将元组转换成字符串形式
#回显
s.sendto("echo:"+data,client)

2、使用socket模块编写的UDP客户端代码:

#! /usr/bin/env python
#coding=utf-8
#客户端,基于UDP协议
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto("hello",("localhost",10000))
data,addr=s.recvfrom(1024)
print "receive data:%s  from %s" %(data,str(addr))

3、使用socket模块编写的TCP服务端

#! /usr/bin/env python
#coding=utf-8
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
#也可以使用s=socket.socket()来通过默认参数来生成TCP的流套接字
#host=''   host可以为空,表示bind()函数可以绑定在所有有效地地址上
host="localhost"
port=1235
s.bind((host,port))   #注意,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()

4、使用socket模块编写的TCP客户端;

#! /usr/bin/env python
#coding=utf-8
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
#服务器的主机名和端口

host="localhost"
port=1235
s.connect((host,port))
s.send("i am client")
data=s.recv(1024)
print "Reply from server-----%s"  %data
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: