c语言的socket基础 http://haoningabc.iteye.com/blog/2305026
使用python
一言不合上代码
server.py
import socket s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host,port)) s.listen(5) while True: c, addr = s.accept()#阻塞 print 'Got connection from', addr print c.recv(1024)#阻塞 c.close()
客户端
client.py
import socket,sys s = socket.socket() host = socket.gethostname() port = 1234 s.connect((host,port)) #hi=raw_input('hello? ') hi=sys.stdin.readline()[:-1] s.send(hi)
代码效果一样
accept阻塞等待客户端
一个客户单就会建立一个c(connection)
最终服务端会变成
一个socket和多个connection
但是还是有顺序,阻塞问题
换上select解决阻塞
import socket,select s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host,port)) s.listen(5) inputs = [s] #print str(s) while True: #rs=[] print "while starting....." rs, ws, es = select.select(inputs,[],[]) #print("rs:"+str(rs)) print("rs len:"+str(len(rs))) for r in rs: if r is s: c, addr = s.accept() print 'print Got connection from', addr inputs.append(c) else: #print "r is not sssssssssssssss" try: data = r.recv(1024) disconnected = not data except socket.error: disconnected = True if disconnected: print "print " ,r.getpeername(), 'disconnected' inputs.remove(r) else: print "print ",data
每次accept第一次阻塞完成取得connection后,就放到一个select监控数组里面
下一次循环的时候进入recv阻塞
使
所有的connection都变成recv
最终,任何一个client有数据接收都会马上收到相应,不会阻塞到某一个连接上,
相当于同时开了多个connection
一个好玩的tunproxy,使用select写的
http://www.secdev.org/projects/tuntap_udp/
把tun设备和socket用select关联起来
http://www.secdev.org/projects/tuntap_udp/files/tunproxy.py