由于最近要开发一款服务器、多客户端应用,自然而然地想到了要用Socket模块。
此模块官方有资料,详见socket --- 底层网络接口 — Python 3.9.5 文档。函数 socket()
返回一个 套接字对象 ,其方法是对各种套接字系统调用的实现。
具体操作如下:
一、客户端编程
1.创建Socket
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
上述代码使用了下面两个属性来创建 Socket:
- 地址簇 : AF_INET (IPv4)
- 类型: SOCK_STREAM (使用 TCP 传输控制协议)
2.错误处理
如果 socket 函数失败了,python 将抛出一个名为 socket.error 的异常,这个异常必须予以处理:
1 #handling errors in python socket programs 2 3 import socket #for sockets 4 import sys #for exit 5 6 try: 7 #create an AF_INET, STREAM socket (TCP) 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 except socket.error, msg: 10 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 11 sys.exit(); 12 13 print 'Socket Created'
3.连接到服务器
连接到服务器需要服务器地址和端口号。
1 import socket #for sockets 2 import sys #for exit 3 4 try: 5 #create an AF_INET, STREAM socket (TCP) 6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 except socket.error, msg: 8 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 9 sys.exit(); 10 11 print 'Socket Created' 12 #or IP here 13 host = 'www.oschina.net' 14 15 try: 16 remote_ip = socket.gethostbyname( host ) 17 18 except socket.gaierror: 19 #could not resolve 20 print 'Hostname could not be resolved. Exiting' 21 sys.exit() 22 23 print 'Ip address of ' + host + ' is ' + remote_ip
此时我们已经有了IP地址,接下来还需要端口信息。
1 import socket #for sockets 2 import sys #for exit 3 4 try: 5 #create an AF_INET, STREAM socket (TCP) 6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 except socket.error, msg: 8 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 9 sys.exit(); 10 11 print 'Socket Created' 12 13 host = 'www.oschina.net' 14 port = 80 15 16 try: 17 remote_ip = socket.gethostbyname( host ) 18 19 except socket.gaierror: 20 #could not resolve 21 print 'Hostname could not be resolved. Exiting' 22 sys.exit() 23 24 print 'Ip address of ' + host + ' is ' + remote_ip 25 26 #Connect to remote server 27 s.connect((remote_ip , port)) 28 29 print 'Socket Connected to ' + host + ' on ip ' + remote_ip
运行后得到的结果如下。
$ python client.py Socket Created Ip address of www.oschina.net is 61.145.122.155 Socket Connected to www.oschina.net on ip 61.145.122.155
这段程序创建了一个 Socket 并进行连接,已经连接上了,接下来就是往服务器上发送数据。
4.发送数据。
sendall 函数用于简单的发送数据,我们来向 oschina 发送一些数据:
1 import socket #for sockets 2 import sys #for exit 3 4 try: 5 #create an AF_INET, STREAM socket (TCP) 6 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 except socket.error, msg: 8 print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] 9 sys.exit(); 10 11 print 'Socket Created' 12 13 host = 'www.oschina.net' 14 port = 80 15 16 try: 17 remote_ip = socket.gethostbyname( host ) 18 19 except socket.gaierror: 20 #could not resolve 21 print 'Hostname could not be resolved. Exiting' 22 sys.exit() 23 24 print 'Ip address of ' + host + ' is ' + remote_ip 25 26 #Connect to remote server 27 s.connect((remote_ip , port)) 28 29 print 'Socket Connected to ' + host + ' on ip ' + remote_ip 30 31 #Send some data to remote server 32 message = "GET / HTTP/1.1\r\n\r\n" 33 34 try : 35 #Set the whole string 36 s.sendall(message.encode("utf-8"))
37 except socket.error: 38 #Send failed 39 print 'Send failed' 40 sys.exit() 41 42 print 'Message send successfully'
注意:s.sendall函数里面的内容必须加上.encode("utf-8"),否则会报错。
上述例子中,首先连接到目标服务器,然后发送字符串数据 "GET / HTTP/1.1\r\n\r\n" ,这是一个 HTTP 协议的命令,用来获取网站首页的内容。
接下来需要读取服务器返回的数据。
5.接收数据
recv 函数用于从 socket 接收数据:
1 #Socket client example in python 2 3 import socket #for sockets 4 import sys #for exit 5 6 #create an INET, STREAMing socket 7 try: 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 except socket.error: 10 print 'Failed to create socket' 11 sys.exit() 12 13 print 'Socket Created' 14 15 host = 'oschina.net'; 16 port = 80; 17 18 try: 19 remote_ip = socket.gethostbyname( host ) 20 21 except socket.gaierror: 22 #could not resolve 23 print 'Hostname could not be resolved. Exiting' 24 sys.exit() 25 26 #Connect to remote server 27 s.connect((remote_ip , port)) 28 29 print 'Socket Connected to ' + host + ' on ip ' + remote_ip 30 31 #Send some data to remote server 32 message = "GET / HTTP/1.1\r\nHost: oschina.net\r\n\r\n" 33 34 try : 35 #Set the whole string 36 s.sendall(message) 37 except socket.error: 38 #Send failed 39 print 'Send failed' 40 sys.exit() 41 42 print 'Message send successfully' 43 44 #Now receive data 45 reply = s.recv(4096) 46 47 print reply
下面是上述程序执行的结果:
$ python client.py
Socket Created
Ip address of oschina.net is 61.145.122.
Socket Connected to oschina.net on ip 61.145.122.155
Message send successfully
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Wed, 24 Oct 2012 13:26:46 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Keep-Alive: timeout=20
Location: http://www.oschina.net/
http://oschina.net 回应了我们所请求的 URL 的内容,很简单。数据接收完了,可以关闭 Socket 了。
6.关闭SOCKET
close 函数用于关闭 Socket:
s.close()
二、服务器端编程
服务器端编程主要包括下面几步:
- 打开 socket
- 绑定到一个地址和端口
- 侦听进来的连接
- 接受连接
- 读写数据
我们已经学习过如何打开 Socket 了,下面是绑定到指定的地址和端口上。
绑定 Socket
bind 函数用于将 Socket 绑定到一个特定的地址和端口,它需要一个类似 connect 函数所需的 sockaddr_in 结构体。
示例代码:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 10 try: 11 s.bind((HOST, PORT)) 12 except socket.error , msg: 13 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] 14 sys.exit() 15 16 print 'Socket bind complete'
绑定完成后,就需要让 Socket 开始侦听连接。很显然,你不能将两个不同的 Socket 绑定到同一个端口之上。
连接侦听
绑定 Socket 之后就可以开始侦听连接,我们需要将 Socket 变成侦听模式。socket 的 listen 函数用于实现侦听模式:
1 s.listen(10) 2 print 'Socket now listening'
listen 函数所需的参数成为 backlog,用来控制程序忙时可保持等待状态的连接数。这里我们传递的是 10,意味着如果已经有 10 个连接在等待处理,那么第 11 个连接将会被拒绝。当检查了 socket_accept 后这个会更加清晰。
接受连接
示例代码:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 10 try: 11 s.bind((HOST, PORT)) 12 except socket.error , msg: 13 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] 14 sys.exit() 15 16 print 'Socket bind complete' 17 18 s.listen(10) 19 print 'Socket now listening' 20 21 #wait to accept a connection - blocking call 22 conn, addr = s.accept() 23 24 #display client information 25 print 'Connected with ' + addr[0] + ':' + str(addr[1])
输出
运行该程序将会显示
$ python server.py
Socket created
Socket bind complete
Socket now listening
现在这个程序开始等待连接进入,端口是 8888,请不要关闭这个程序,我们来通过 telnet 程序来进行测试。
打开命令行窗口并输入:
$ telnet localhost 8888
It will immediately show
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
而服务器端窗口显示的是:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:59954
我们可看到客户端已经成功连接到服务器。
上面例子我们接收到连接并立即关闭,这样的程序没什么实际的价值,连接建立后一般会有大量的事情需要处理,因此让我们来给客户端做出点回应吧。
sendall 函数可通过 Socket 给客户端发送数据:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 10 try: 11 s.bind((HOST, PORT)) 12 except socket.error , msg: 13 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] 14 sys.exit() 15 16 print 'Socket bind complete' 17 18 s.listen(10) 19 print 'Socket now listening' 20 21 #wait to accept a connection - blocking call 22 conn, addr = s.accept() 23 24 print 'Connected with ' + addr[0] + ':' + str(addr[1]) 25 26 #now keep talking with the client 27 data = conn.recv(1024) 28 conn.sendall(data) 29 30 conn.close() 31 s.close()
继续运行上述代码,然后打开另外一个命令行窗口输入下面命令:
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
happy
Connection closed by foreign host.
可看到客户端接收到来自服务器端的回应内容。
上面的例子还是一样,服务器端回应后就立即退出了。而一些真正的服务器像 http://www.oschina.net 是一直在运行的,时刻接受连接请求。
也就是说服务器端应该一直处于运行状态,否则就不能成为“服务”,因此我们要让服务器端一直运行,最简单的方法就是把 accept 方法放在一个循环内。
一直在运行的服务器
对上述代码稍作改动:
1 import socket 2 import sys 3 4 HOST = '' # Symbolic name meaning all available interfaces 5 PORT = 8888 # Arbitrary non-privileged port 6 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 print 'Socket created' 9 10 try: 11 s.bind((HOST, PORT)) 12 except socket.error , msg: 13 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] 14 sys.exit() 15 16 print 'Socket bind complete' 17 18 s.listen(10) 19 print 'Socket now listening' 20 21 #now keep talking with the client 22 while 1: 23 #wait to accept a connection - blocking call 24 conn, addr = s.accept() 25 print 'Connected with ' + addr[0] + ':' + str(addr[1]) 26 27 data = conn.recv(1024) 28 reply = 'OK...' + data 29 if not data: 30 break 31 32 conn.sendall(reply) 33 34 conn.close() 35 s.close()
很简单只是加多一个 while 1 语句而已。
继续运行服务器,然后打开另外三个命令行窗口。每个窗口都使用 telnet 命令连接到服务器:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
happy
OK .. happy
Connection closed by foreign host.
服务器所在的终端窗口显示的是:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60225
Connected with 127.0.0.1:60237
Connected with 127.0.0.1:60239
你看服务器再也不退出了,好吧,用 Ctrl+C 关闭服务器,所有的 telnet 终端将会显示 "Connection closed by foreign host."
已经很不错了,但是这样的通讯效率太低了,服务器程序使用循环来接受连接并发送回应,这相当于是一次最多处理一个客户端的请求,而我们要求服务器可同时处理多个请求。
处理多个连接
为了处理多个连接,我们需要一个独立的处理代码在主服务器接收到连接时运行。一种方法是使用线程,服务器接收到连接然后创建一个线程来处理连接收发数据,然后主服务器程序返回去接收新的连接。
下面是我们使用线程来处理连接请求:
1 import socket 2 import sys 3 from thread import * 4 5 HOST = '' # Symbolic name meaning all available interfaces 6 PORT = 8888 # Arbitrary non-privileged port 7 8 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 9 print 'Socket created' 10 11 #Bind socket to local host and port 12 try: 13 s.bind((HOST, PORT)) 14 except socket.error , msg: 15 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] 16 sys.exit() 17 18 print 'Socket bind complete' 19 20 #Start listening on socket 21 s.listen(10) 22 print 'Socket now listening' 23 24 #Function for handling connections. This will be used to create threads 25 def clientthread(conn): 26 #Sending message to connected client 27 conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string 28 29 #infinite loop so that function do not terminate and thread do not end. 30 while True: 31 32 #Receiving from client 33 data = conn.recv(1024) 34 reply = 'OK...' + data 35 if not data: 36 break 37 38 conn.sendall(reply) 39 40 #came out of loop 41 conn.close() 42 43 #now keep talking with the client 44 while 1: 45 #wait to accept a connection - blocking call 46 conn, addr = s.accept() 47 print 'Connected with ' + addr[0] + ':' + str(addr[1]) 48 49 #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. 50 start_new_thread(clientthread ,(conn,)) 51 52 s.close()
运行上述服务端程序,然后像之前一样打开三个终端窗口并执行 telent 命令:
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Welcome to the server. Type something and hit enter
hi
OK...hi
asd
OK...asd
cv
OK...cv
服务器端所在终端窗口输出信息如下:
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:60730
Connected with 127.0.0.1:60731
线程接管了连接并返回相应数据给客户端。
这便是我们所要介绍的服务器端编程。