php中socket是什么?
PHP中Socket是在应用层和传输层之间的一个抽象层,它可以把“TCP/IP”层复杂的操作抽象为几个简单的接口,供应用层调用实现进程在网络中的通信。
什么是 Socket?
Socket 的中文翻译过来就是“套接字”。套接字是什么,我们先来看看它的英文含义:插座。
Socket 就像一个电话插座,负责连通两端的电话,进行点对点通信,让电话可以进行通信,端口就像插座上的孔,端口不能同时被其他进程占用。而我们建立连接就像把插头插在这个插座上,创建一个 Socket 实例开始监听后,这个电话插座就时刻监听着消息的传入,谁拨通我这个“IP 地址和端口”,我就接通谁。
实际上,Socket 是在应用层和传输层之间的一个抽象层,它把 TCP/IP 层复杂的操作抽象为几个简单的接口,供应用层调用实现进程在网络中的通信。Socket 起源于 UNIX,在 UNIX 一切皆文件的思想下,进程间通信就被冠名为文件描述符(file descriptor),Socket 是一种“打开—读/写—关闭”模式的实现,服务器和客户端各自维护一个“文件”,在建立连接打开后,可以向文件写入内容供对方读取或者读取对方内容,通讯结束时关闭文件。
另外我们经常说到的Socket 所在位置如下图:
Socket 通信过程
Socket 保证了不同计算机之间的通信,也就是网络通信。对于网站,通信模型是服务器与客户端之间的通信。两端都建立了一个 Socket 对象,然后通过 Socket 对象对数据进行传输。通常服务器处于一个无限循环,等待客户端的连接。
一图胜千言,下面是面向连接的 TCP 时序图:
客户端过程:
客户端的过程比较简单,创建 Socket,连接服务器,将 Socket 与远程主机连接(注意:只有 TCP 才有“连接”的概念,一些 Socket 比如 UDP、ICMP 和 ARP 没有“连接”的概念),发送数据,读取响应数据,直到数据交换完毕,关闭连接,结束 TCP 对话。
import socket import sys if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建 Socket 连接 sock.connect(('127.0.0.1', 8001)) # 连接服务器 while True: data = input('Please input data:') if not data: break try: sock.sendall(data) except socket.error as e: print('Send Failed...', e) sys.exit(0) print('Send Successfully') res = sock.recv(4096) # 获取服务器返回的数据,还可以用 recvfrom()、recv_into() 等 print(res) sock.close() sock.sendall(data)
这里也可用 send() 方法:不同在于 sendall() 在返回前会尝试发送所有数据,并且成功时返回 None,而 send()则返回发送的字节数量,失败时都抛出异常。
服务端过程:
咱再来聊聊服务端的过程,服务端先初始化 Socket,建立流式套接字,与本机地址及端口进行绑定,然后通知 TCP,准备好接收连接,调用 accept() 阻塞,等待来自客户端的连接。如果这时客户端与服务器建立了连接,客户端发送数据请求,服务器接收请求并处理请求,然后把响应数据发送给客户端,客户端读取数据,直到数据交换完毕。最后关闭连接,交互结束。
import socket import sys if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建 Socket 连接(TCP) print('Socket Created') try: sock.bind(('127.0.0.1', 8001)) # 配置 Socket,绑定 IP 地址和端口号 except socket.error as e: print('Bind Failed...', e) sys.exit(0) sock.listen(5) # 设置最大允许连接数,各连接和 Server 的通信遵循 FIFO 原则 while True: # 循环轮询 Socket 状态,等待访问 conn, addr = sock.accept() try: conn.settimeout(10) # 如果请求超过 10 秒没有完成,就终止操作 # 如果要同时处理多个连接,则下面的语句块应该用多线程来处理 while True: # 获得一个连接,然后开始循环处理这个连接发送的信息 data = conn.recv(1024) print('Get value ' + data, end='nn') if not data: print('Exit Server', end='nn') break conn.sendall('OK') # 返回数据 except socket.timeout: # 建立连接后,该连接在设定的时间内没有数据发来,就会引发超时 print('Time out') conn.close() # 当一个连接监听循环退出后,连接可以关掉 sock.close()conn, addr = sock.accept()
调用 accept() 时,Socket 会进入waiting状态。客户端请求连接时,方法建立连接并返回服务器。accept() 返回一个含有两个元素的元组 (conn, addr)。第一个元素 conn 是新的 Socket 对象,服务器必须通过它与客户端通信;第二个元素 addr 是客户端的 IP 地址及端口。data = conn.recv(1024)
接下来是处理阶段,服务器和客户端通过 send() 和 recv() 通信(传输数据)。
服务器调用 send(),并采用字符串形式向客户端发送信息,send() 返回已发送的字符个数。
服务器调用 recv() 从客户端接收信息。调用 recv() 时,服务器必须指定一个整数,它对应于可通过本次方法调用来接收的最大数据量。recv() 在接收数据时会进入blocked状态,最后返回一个字符串,用它表示收到的数据。如果发送的数据量超过了 recv() 所允许的,数据会被截短。多余的数据将缓冲于接收端,以后调用 recv() 时,会继续读剩余的字节,如果有多余的数据会从缓冲区删除(以及自上次调用 recv() 以来,客户端可能发送的其它任何数据)。传输结束,服务器调用 Socket 的 close() 关闭连接。
从 TCP 连接的视角看 Socket 过程:
TCP 三次握手的 Socket 过程:
服务器调用 socket()、bind()、listen() 完成初始化后,调用 accept() 阻塞等待;
客户端 Socket 对象调用 connect() 向服务器发送了一个 SYN 并阻塞;
服务器完成了第一次握手,即发送 SYN 和 ACK 应答;
客户端收到服务端发送的应答之后,从 connect() 返回,再发送一个 ACK 给服务器;
服务器 Socket 对象接收客户端第三次握手 ACK 确认,此时服务端从 accept() 返回,建立连接。
接下来就是两个端的连接对象互相收发数据。
TCP 四次挥手的 Socket 过程:
某个应用进程调用 close() 主动关闭,发送一个 FIN;
另一端接收到 FIN 后被动执行关闭,并发送 ACK 确认;
之后被动执行关闭的应用进程调用 close() 关闭 Socket,并也发送一个 FIN;
接收到这个 FIN 的一端向另一端 ACK 确认。
总结:
上面的代码简单地演示了 Socket 的基本函数使用,其实不管有多复杂的网络程序,这些基本函数都会用到。上面的服务端代码只有处理完一个客户端请求才会去处理下一个客户端的请求,这样的服务器处理能力很弱,而实际中服务器都需要有并发处理能力,为了达到并发处理,服务器就需要 fork 一个新的进程或者线程去处理请求。
更多相关知识,请访问 PHP中文网!!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
