python-socket

socket基本流程
客户端和服务端的交互
SocketServer实现异步多线程服务端
SocketServer上传文件html

socket实现ftp服务器python

基本上,Socket 是任何一种计算机网络通信中最基础的内容。例如当你在浏览器地址栏中输入URL 时,你会打开一个套接字,而后链接到 URL 并读取响应的页面而后而后显示出来。而其余一些聊天客户端如 gtalk 和 skype 也是相似。任何网络通信都是经过 Socket 来完成的。nginx

建立 Socket

首先要作的就是建立一个 Socket,socket 的 socket 函数能够实现,代码以下:编程

1 #Socket client example in python
2 import socket   #for sockets
3  
4 #create an AF_INET, STREAM socket (TCP)
5 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6      
7 print 'Socket Created'
View Code

函数 socket.socket 建立了一个 Socket,并返回 Socket 的描述符可用于其余 Socket 相关的函数。浏览器

上述代码使用了下面两个属性来建立 Socket:服务器

地址簇 : AF_INET (IPv4)
类型: SOCK_STREAM (使用 TCP 传输控制协议)网络

错误处理多线程

若是 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'
View Code

好了,假设你已经成功建立了 Socket,下一步该作什么呢?接下来咱们将使用这个 Socket 来链接到服务器。app

注意

与 SOCK_STREAM 相对应的其余类型是 SOCK_DGRAM 用于 UDP 通信协议,UDP 通信是非链接 Socket,在这篇文章中咱们只讨论 SOCK_STREAM ,或者叫 TCP 。

链接到服务器

链接到服务器须要服务器地址和端口号,这里使用的是 www.oschina.net 和 80 端口。

首先获取远程主机的 IP 地址

链接到远程主机以前,咱们须要知道它的 IP 地址,在 Python 中,获取 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      
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
View Code

咱们已经有 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
View Code

如今运行程序

1 $ python client.py
2 Socket Created
3 Ip address of www.oschina.net is 61.145.122.155
4 Socket Connected to www.oschina.net on ip 61.145.122.155
View Code

这段程序建立了一个 Socket 并进行链接,试试使用其余一些不存在的端口(如81)会是怎样?这个逻辑至关于构建了一个端口扫描器。

已经链接上了,接下来就是往服务器上发送数据。

免费提示

使用 SOCK_STREAM/TCP 套接字才有“链接”的概念。链接意味着可靠的数据流通信机制,能够同时有多个数据流。能够想象成一个数据互不干扰的管道。另一个重要的提示是:数据包的发送和接收是有顺序的。

其余一些 Socket 如 UDP、ICMP 和 ARP 没有“链接”的概念,它们是无链接通信,意味着你可从任何人或者给任何人发送和接收数据包。

发送数据

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)
37 except socket.error:
38     #Send failed
39     print 'Send failed'
40     sys.exit()
41  
42 print 'Message send successfully'
View Code

上述例子中,首先链接到目标服务器,而后发送字符串数据 "GET / HTTP/1.1\r\n\r\n" ,这是一个 HTTP 协议的命令,用来获取网站首页的内容。

接下来须要读取服务器返回的数据。

接收数据

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
View Code

下面是上述程序执行的结果:

 1 $ python client.py
 2 Socket Created
 3 Ip address of oschina.net is 61.145.122.
 4 Socket Connected to oschina.net on ip 61.145.122.155
 5 Message send successfully
 6 HTTP/1.1 301 Moved Permanently
 7 Server: nginx
 8 Date: Wed, 24 Oct 2012 13:26:46 GMT
 9 Content-Type: text/html
10 Content-Length: 178
11 Connection: keep-alive
12 Keep-Alive: timeout=20
13 Location: http://www.oschina.net/
View Code

oschina.net 回应了咱们所请求的 URL 的内容,很简单。数据接收完了,能够关闭 Socket 了。

关闭 socket

close 函数用于关闭 Socket:

1 s.close()

这就是了。

让咱们回顾一下

上述的示例中咱们学到了如何:

1. 建立 Socket
2. 链接到远程服务器
3. 发送数据
4. 接收回应

当你用浏览器打开 www.oschina.net 时,其过程也是同样。包含两种类型,分别是客户端和服务器,客户端链接到服务器并读取数据,服务器使用 Socket 接收进入的链接并提供数据。所以在这里 www.oschina.net 是服务器端,而你的浏览器是客户端。

接下来咱们开始在服务器端作点编码。

服务器端编程

服务器端编程主要包括下面几步:

1. 打开 socket
2. 绑定到一个地址和端口
3. 侦听进来的链接
4. 接受链接
5. 读写数据

咱们已经学习过如何打开 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'
View Code

绑定完成后,就须要让 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])
View Code

输出

运行该程序将会显示:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening

如今这个程序开始等待链接进入,端口是 8888,请不要关闭这个程序,咱们来经过 telnet 程序来进行测试。

打开命令行窗口并输入:

1 $ telnet localhost 8888
2  
3 It will immediately show
4 $ telnet localhost 8888
5 Trying 127.0.0.1...
6 Connected to localhost.
7 Escape character is '^]'.
8 Connection closed by foreign host.

而服务器端窗口显示的是:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening
5 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()
View Code

继续运行上述代码,而后打开另一个命令行窗口输入下面命令:

1 $ telnet localhost 8888
2 Trying 127.0.0.1...
3 Connected to localhost.
4 Escape character is '^]'.
5 happy
6 happy
7 Connection closed by foreign host.

可看到客户端接收到来自服务器端的回应内容。

上面的例子仍是同样,服务器端回应后就当即退出了。而一些真正的服务器像 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()
View Code

很简单只是加多一个 while 1 语句而已。

继续运行服务器,而后打开另外三个命令行窗口。每一个窗口都使用 telnet 命令链接到服务器:

1 $ telnet localhost 5000
2 Trying 127.0.0.1...
3 Connected to localhost.
4 Escape character is '^]'.
5 happy
6 OK .. happy
7 Connection closed by foreign host.

 

服务器所在的终端窗口显示的是:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening
5 Connected with 127.0.0.1:60225
6 Connected with 127.0.0.1:60237
7 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()
View Code

运行上述服务端程序,而后像以前同样打开三个终端窗口并执行 telent 命令:

01 $ telnet localhost 8888
02 Trying 127.0.0.1...
03 Connected to localhost.
04 Escape character is '^]'.
05 Welcome to the server. Type something and hit enter
06 hi
07 OK...hi
08 asd
09 OK...asd
10 cv
11 OK...cv

服务器端所在终端窗口输出信息以下:

1 $ python server.py
2 Socket created
3 Socket bind complete
4 Socket now listening
5 Connected with 127.0.0.1:60730
6 Connected with 127.0.0.1:60731

 

线程接管了链接并返回相应数据给客户端。

这即是咱们所要介绍的服务器端编程。

结论

你可能会碰见一些问题:Bind failed. Error Code : 98 Message Address already in use,遇见这种问题只须要简单更改服务器端口便可。

相关文章
相关标签/搜索