1、使用socket模块编写UDP服务端,代码如下。从中需要注意的知识是:bind()和connect()函数都只有一个参数,参数是表示地址的元组(hostname,port),千万不要写成两个参数了。
01 | #! /usr/bin/env python |
02 | #coding=utf-8 |
03 | #使用socket模块编写的服务器(通过UDP传输数据) |
04 | import socket |
05 | s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) |
06 | s.bind(("", 10000 )) #bind函数只有一个参数 |
07 | while True : |
08 | data,client = s.recvfrom( 1024 ) |
09 | print "receive a connection from %s" % str (client) #str()函数可以将元组转换成字符串形式 |
10 | #回显 |
11 | s.sendto( "echo:" + data,client) |
2、使用socket模块编写的UDP客户端代码:
1 | #! /usr/bin/env python |
2 | #coding=utf-8 |
3 | #客户端,基于UDP协议 |
4 | import socket |
5 | s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) |
6 | s.sendto( "hello" ,( "localhost" , 10000 )) |
7 | data,addr = s.recvfrom( 1024 ) |
8 | print "receive data:%s from %s" % (data, str (addr)) |
3、使用socket模块编写的TCP服务端
01 | #! /usr/bin/env python |
02 | #coding=utf-8 |
03 | import socket |
04 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM, 0 ) |
05 | #也可以使用s=socket.socket()来通过默认参数来生成TCP的流套接字 |
06 | #host='' host可以为空,表示bind()函数可以绑定在所有有效地地址上 |
07 | host = "localhost" |
08 | port = 1235 |
09 | s.bind((host,port)) #注意,bind函数的参数只有一个,是(host,port)的元组 |
10 | s.listen( 3 ) |
11 | while True : |
12 | client,ipaddr = s.accept() |
13 | print "Got a connect from %s" % str (ipaddr) |
14 | data = client.recv( 1024 ) |
15 | print "receive data:%s" % data |
16 | client.send( "echo:" + data) |
17 | client.close() |
4、使用socket模块编写的TCP客户端;
01 | #! /usr/bin/env python |
02 | #coding=utf-8 |
03 | import socket |
04 | s = socket.socket(socket.AF_INET,socket.SOCK_STREAM, 0 ) |
05 | #服务器的主机名和端口 |
06 |
07 | host = "localhost" |
08 | port = 1235 |
09 | s.connect((host,port)) |
10 | s.send( "i am client" ) |
11 | data = s.recv( 1024 ) |
12 | print "Reply from server-----%s" % data |