Socket的英文原义是“孔”或“插座”。作为BSD UNIX的进程通信机制,取后一种意思。通常也称作”套接字”,用于描述IP地址和端口,是一个通信链的句柄。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。Socket正如其英文原意那样,像一个多孔插座。一台主机犹如布满各种插座的房间,每个插座有一个编号,有的插座提供220伏交流电, 有的提供110伏交流电,有的则提供有线电视节目。 客户软件将插头插到不同编号的插座,就可以得到不同的服务。–百度百科
socket如此重要,现在的网络编程几乎都是用的它,它起源于Unix,而Unix/Linux基本哲学之一就是“一切皆文件”,都可以用打开,读写,关闭的模式来操作。然而,对于网络服务来说,往往针对大量的客户群体,例如web,对于这类服务,必须要保证既能并行处理请求,又能保证服务的稳定。但传统的socket在处理并发方面有所欠缺,借助与select模块,能够较好的是要非阻塞的IO。
Python中的select模块以列表形式接受四个参数,分别是需要监控的可读文件对象,可写文件对象,产生异常的文件对象和超时设置,当监控的对象发生变化时,select会返回发生变化的对象列表。下面是用select实现一个简单的聊天室:
#!/usr/bin/env python #*-* coding:utf-8 *-* import socket import select import sys import signal class ChatServer(): def __init__(self,host,port,timeout=10,backlog=5): #记录连接的客户端数量 self.clients =0 #存储连接的客户端socket和地址对应的字典 self.clientmap={} #存储连接的客户端socket self.outputs = [] #建立socket self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) self.server.bind((host,port)) self.server.listen(backlog) #增加信号处理 signal.signal(signal.SIGINT,self.sighandler) def sighandler(self): sys.stdout.write("Shutdown Server......\n") #向已经连接客户端发送关系信息,并主动关闭socket for output in self.outputs: output.send("Shutdown Server") output.close() #关闭listen self.server.close() sys.stdout.flush() #主函数,用来启动服务器 def run(self): #需要监听的可读对象 inputs=[self.server] runing=True #添加监听主循环 while runing: try: readable,writeable,exceptional = select.select(inputs,self.outputs,[]) #此处会被select模块阻塞,只有当监听的三个参数发生变化时,select才会返回 except select.error,e: break #当返回的readable中含有本地socket的信息时,表示有客户端正在请求连接 if self.server in readable: #接受客户端连接请求 client,addr=self.server.accept() sys.stdout.write("New Connection from %s\n"%str(addr)) sys.stdout.flush() #更新服务器上客户端连接情况 #1,数量加1 #2,self.outputs增加一列 #3,self.clientmap增加一对 #4, 给input添加可读监控 self.clients += 1 self.outputs.append(client) self.clientmap[client]=addr inputs.append(client) #readable中含有已经添加的客户端socket,并且可读 #说明 1,客户端有数据发送过来或者 2,客户端请求关闭 elif len(readable) != 0: #1, 取出这个列表中的socket csock=readable[0] #2, 根据这个socket,在事先存放的clientmap中,去除客户端的地址,端口的详细信息 host,port = self.clientmap[csock] #3,取数据, 或接受关闭请求,并处理 #注意,这个操作是阻塞的,但是由于数据是在本地缓存之后,所以速度会非常快 try: data = csock.recv(1024).strip() for cs in self.outputs: if cs != csock: cs.send("%s\n"%data) except socket.error,e: self.clients -= 1 inputs.remove(csock) self.outputs.remove(csock) del self.clientmap[csock] #print self.outputs self.server.close() if __name__ == "__main__": chat=ChatServer("",8008) chat.run()
运行这个脚本,然后用任意客户端如telnet或netcat连接8008端口,多个客户端之间就可以进行对话。
其实select模块本身是阻塞的,当需要监控的socket发生变化时,select作出返回,下面的程序会继续执行,程序根据select的返回值,对各种情况作出处理。

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor