您的位置:首页 > 理论基础 > 计算机网络

python 网络编程基础 笔记

2012-11-24 13:47 573 查看
第二章:网络客户端
建立socket(TCP client):

import socket

print "Creating socket ......"s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)print "done"

print "looking up port number ......"port = socket.getservbyname('http', 'tcp')print "done"

print "Connect to remote host on port %d ......" % ports.connect(('www.baidu.com', port))print "done"

print "Connected from", s.getsockname()print "Connected to", s.getpeername()

s.sendall('/' + "\r\n")
//获取当前根目录下文件列表

s.shutdown(1) //数据调用shutdown函数才能确保发送

while 1:buf = s.recv(2048)if not len(buf): breaksys.stdout.write(buf)

建立socket对象时,需要告诉系统通信类型(IPv4 or IPv6)和协议家族(TCP or UDP)

AF_INET代表IPv4

SOCK_STREAM代表TCP, SOCK_DGRAM代表UDP

getservbyname(服务名,协议)函数可以自动查询服务对应端口

getsockname()函数返回本地的IP和端口号

getpeername()函数返回远程机器的IP和端口号

 

 

 

第三章 网络服务器
TCP Server:

import sys

import socket

host = '' //bind to all interface

port = 51423

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

// SOL_SOCKET使用socket选项

// SO_REUSEADD当socket关闭时,本地用户该socket的端口可以重用(保留一段时间该端口)0代表true(马上释放端口),
1代表false

s.bind((host,port))

print "Waiting for connections..."

s.listen(1)//准备接受连接,参数1代表服务器实际处理请求是允许多少等待连接,一般操作系统不支持大于5

while 1:

try:

clientsock, clientaddr = s.accept()//当有client连接返回

except KeyboardInterrupt:

raise

except:

traceback.print_exc()

continue

# Process the connection

try:

print "got connection from", clientsock.getpeername()

//('127.0.0.1', 39675) clientsock.getpeername()返回client ip, port

except (KeyboardIntertupt, SystemExit):

raise

except:

traceback.print_exc()

#Close the connection

try:

clientsock.close()

except KeyboardIntertupt:

raise

except:

traceback.print_exc()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python