python socket 学习(1)

part 1: 最简单的socket 收发

server.py:

importsocket

s = socket.socket()

host = socket.gethostname()

port = 8001

s.bind((host,port))

s.listen( 5 )

while True :
c, addr = s.accept()
print ' connection from ' , addr
c.send( 'thank you for connection' )
c.close

client.py

importsocket

s = socket.socket()

host = socket.gethostname()
port =8001

s.connect((host,port))

prints.recv((1024))

part 2: socket 锁定


其实不存在socket 锁定,只是通过一个线程锁定来实现的!!


>>> import threading
>>> with threading.Lock():
... print 'if'
...
if
>>> sock_mutex = threading.Lock()
>>> with sock_mutex:
... print 'if'
...
if

part 3: 使用select 的异步IO

# -*- coding:utf-8 -*-
importsocket
import select # 1

if __name__ == '__main__' :
print "server running ..."
#pythonselect 实现非阻塞

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(( 'localhost' , 8001 ))
sock.listen( 5 )
while True :
# 2
infds,outfds,errfds = select.select([sock,],[],[], 15 )
# 3
# 每次调用这个方法,
if len(infds) != 0 :
print 'if ...'
connection,address = sock.accept()
try :
connection.settimeout( 5 )
buf = connection.recv( 1024 )
print "buf: %s" % buf
connection.send( 'welcome to server!' )
except socket.timeout:
print 'time out'
connection.close()
else :
print 'no data coming'

part 4: 关于select 的详解:

NAME
select - This module supports asynchronous I/O on multiple file descriptors.

FILE
(built-in)

DESCRIPTION
*** IMPORTANT NOTICE ***
On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.

FUNCTIONS
poll(...)
Returns a polling object, which supports registering and
unregistering file descriptors, and then polling them for I/O events.

select(...)
select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)

Wait until one or more file descriptors are ready for some kind of I/O.
The first three arguments are sequences of file descriptors to be waited for:
rlist -- wait until ready for reading
wlist -- wait until ready for writing
xlist -- wait for an ``exceptional condition''
If only one kind of condition is required, pass [] for the other lists.
A file descriptor is either a socket or file object, or a small integer
gotten from a fileno() method call on one of those.

The optional 4th argument specifies a timeout in seconds; it may be
a floating point number to specify fractions of seconds. If it is absent
or None, the call will never time out.

The return value is a tuple of three lists corresponding to the first three
arguments; each contains the subset of the corresponding file descriptors
that are ready.

*** IMPORTANT NOTICE ***
On Windows and OpenVMS, only sockets are supported; on Unix, all file
descriptors can be used.

# 这里着重说一下 select. 对于异步io, 在select()的第一个参数中传入一个 sock的list, wlist, xlist 均为空, 第四个参数为定期监听的时间;
select 返回值为 由 rlist,wlist, xlist 三个列表组成的一个tuple;
大多说情况下,只要 rlist 是否有值就可以了!

infds,outfds,errfds = select.select([sock,],[],[],15)
if len(infds) != 0 :
# 这里的fd , 表示file descripters.

part 5: socket sender receiver 分离

# 自己试着把一client 简单的分成sender,py receiver,py. 结果是不行的。 使用socket 通行时server client 操作的是一个通道。

想想之前java 实现socket 通信也是一样的道理。 之前CWT 写成sender,receiver 模式是有背景和条件的。呵呵,当时太浅薄了,竟然没有多想就接受了这种模式。


part 6: errno 的学习

# 定义一些和操作系统相关的错误码:

NAME
errno - This module makes available standard errno system symbols.

FILE
(built-in)

MODULE DOCS
http://docs.python.org/library/errno

DESCRIPTION
The value of each symbol is the corresponding integer value,
e.g., on most systems, errno.ENOENT equals the integer 2.

The dictionary errno.errorcode maps numeric codes to symbol names,
e.g., errno.errorcode[2] could be the string 'ENOENT'.

Symbols that are not relevant to the underlying system are not defined.

To map error codes to error messages, use the function os.strerror(),
e.g. os.strerror(2) could return 'No such file or directory'.

DATA
E2BIG = 7
EACCES = 13
EADDRINUSE = 98
EADDRNOTAVAIL = 99
EADV = 68
EAFNOSUPPORT = 97
EAGAIN = 11


>>> errno.EAGAIN
11

part 7: urllib2 初探


defforward(self, packet):
"""Forward the packet packet toeventer."""
logging.debug("forwarding...")
try:
opener = urllib2.build_opener()
opener.addheaders = [("Content-type","application/xml;charset=utf-8")]
req = urllib2.Request(url=ConfHelper.EVENTER_CONF.url,
data=safe_utf8(packet))
returnopener.open(req).read()
exceptExceptionase:
logging.exception("forward error: %s", e.args)








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值