-
Python办事器开辟三:Socket
添加时间:2013-5-23 点击量:socket是操纵体系中I/O的延续,它可以使过程和机械之间的通信成为可能。socket可以算作一个标准的文件描述符。不合的是文件须要用open()函数打开,而socket用socket()
函数建树.recv()、send()函数和read()、write()函数极为类似。
TCP一般经由过程accept()来为每个连接的客户端建树一个新的scoket。UDP一般只是应用一个单一的socket,完全依附recv()返回的值来断定该往哪里发送响应。
客户端:
1、建树一个socket:
//SOCK_STREAM默示TCP,SOCK_DGRAM默示UDP,AF_INET默示IPv4
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2、连接socket
连接socket须要一个tuple参数,来供给IP和端标语:
s.connect((“www.example.com”, 80))
3、
#!/usr/bin/env python
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 Connecting to remote host on port %d... % port,
s.connect((www.google.com, port))
print done.
#获取本身的IP和端标语
print Connected , s.getsockname()
#获取长途的IP和端标语
print Connected to, s.getpeername()
文件类对象:
import socket, sys
port = 70
host = sys.argv[1]
filename = sys.argv[2]
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
fd = s.makefile(rw, 0)
fd.write(filename + \r\n)
for line in fd.readlines():
sys.stdout.write(line)
高等接口:
import urllib, sys
f = urllib.urlopen(sys.argv[1])
while 1:
buf = f.read(2048)
if not len(buf):
break
sys.stdout.write(buf)
办事器端:
1、建树一个连接:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2、设置socket选项:
//socket 端口可立即复用
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)3、绑定socket:
s.bind((host, port))
4、:
s.listen(1)
5、接管连接:
while 1:
clientsock, clientaddr = s.accept()
print Got connection , clientsock.getpeername()
clientsock.close()6、
#!/usr/bin/env python
import socket, traceback
host = # Bind to all interfaces
port = 51423
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
#这里设定每次最多只有一个等待处理惩罚的恳求,真正的办事器会设置一个很高的数字。
s.listen(1)
while 1:
try:
clientsock, clientaddr = s.accept()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
continue
# Process the connection
try:
print Got connection , clientsock.getpeername()
# Process the request here
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
# Close the connection
try:
clientsock.close()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()应用UDP:
#!/usr/bin/env python
import socket, traceback
host = # Bind to all interfaces
port = 51423
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
while 1:
try:
message, address = s.recv(8192)
print Got data , address
# Echo it back
s.sendto(message, address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
我所有的自负皆来自我的自卑,所有的英雄气概都来自于我的软弱。嘴里振振有词是因为心里满是怀疑,深情是因为痛恨自己无情。这世界没有一件事情是虚空而生的,站在光里,背后就会有阴影,这深夜里一片寂静,是因为你还没有听见声音。—— 马良《坦白书》