现在的位置: 首页 > 综合 > 正文

使用 Python 编写套接字应用程序 套接字和 SocketServer 模块

2019年06月06日 ⁄ 综合 ⁄ 共 947字 ⁄ 字号 评论关闭

Python 的标准模块的 socket 提供了可从 C scoket 中找到的几乎完全相同的功能。不过该接口通常更加灵活,主要是因为它有动态类型化的优点。此外,它还使用了面向对象的风格。例如,一旦您创建一个套接字对象,那么诸如 .bind()、 .connect() 和 .send()之类的方法都是该对象的方法,而不是在某个套接字上执行操作的全局函数。

在相比于 socket 的更高层次上,模块 SocketServer 提供了用于编写服务器的框架。这仍然是相对低级的,还有可用于为更高级的协议提供服务的更高级接口。比如 SimpleHTTPServer、 DocXMLRPCServer 和 CGIHTTPServer

ServerCode.py

import socket,traceback
host=''
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 conncection
    try:
        print "Got connection from ",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()
        

【上篇】
【下篇】

抱歉!评论已关闭.