Python中的套接字编程
套接字编程是一种连接网络上的两个节点以相互通信的方式。一个套接字(节点)在 IP 的特定端口上侦听,而另一个套接字伸手到另一个以形成连接。服务器形成侦听器套接字,而客户端伸手到服务器。
它们是网页浏览背后的真正支柱。简单来说,有一个服务器和一个客户端。
套接字编程是通过导入套接字库并制作一个简单的套接字开始的。
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
这里我们创建了一个套接字实例并传递了两个参数。第一个参数是AF_INET ,第二个参数是SOCK_STREAM 。 AF_INET 指的是地址族 ipv4。 SOCK_STREAM 表示面向连接的 TCP 协议。
现在我们可以使用这个 socket.3 连接到服务器了
连接到服务器:
请注意,如果在创建套接字期间发生任何错误,则创建套接字。抛出错误,我们只能通过知道其 IP 来连接到服务器。您可以使用以下方法找到服务器的 IP:
$ ping www.google.com
您还可以使用Python查找 IP:
import socket
ip = socket.gethostbyname('www.google.com')
print ip
这是连接到 Google 的脚本示例。
Python3
# An example script to connect to Google using socket
# programming in Python
import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except socket.error as err:
print ("socket creation failed with error %s" %(err))
# default port for socket
port = 80
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
# this means could not resolve the host
print ("there was an error resolving the host")
sys.exit()
# connecting to the server
s.connect((host_ip, port))
print ("the socket has successfully connected to google")
Python3
# first of all import the socket library
import socket
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )
# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
# Close the connection with the client
c.close()
# Breaking once connection closed
break
Python3
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
# close the connection
s.close()
输出 :
Socket successfully created
the socket has successfully connected to google
on port == 173.194.40.19
- 首先,我们制作了一个套接字。
- 然后我们解析了谷歌的IP,最后我们连接到谷歌。
- 现在我们需要知道如何通过套接字发送一些数据。
- 对于发送数据,套接字库有一个sendall函数。此函数允许您向套接字连接的服务器发送数据,服务器也可以使用此函数向客户端发送数据。
一个简单的服务器-客户端程序:
服务器 :
服务器有一个 bind() 方法,它将它绑定到特定的 IP 和端口,以便它可以侦听该 IP 和端口上的传入请求。服务器有一个listen() 方法,该方法将服务器置于监听模式。这允许服务器监听传入的连接。最后一个服务器有一个 accept() 和 close() 方法。 accept 方法启动与客户端的连接,close 方法关闭与客户端的连接。
Python3
# first of all import the socket library
import socket
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )
# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
# Close the connection with the client
c.close()
# Breaking once connection closed
break
- 首先,我们导入必要的套接字。
- 然后我们创建了一个套接字对象并在我们的电脑上保留了一个端口。
- 之后,我们将我们的服务器绑定到指定的端口。传递一个空字符串意味着服务器也可以监听来自其他计算机的传入连接。如果我们通过了 127.0.0.1,那么它只会监听本地计算机内的那些调用。
- 之后我们将服务器置于监听模式。这里的 5 表示如果服务器忙,则保持 5 个连接等待,如果第 6 个套接字尝试连接,则连接被拒绝。
- 最后,我们创建一个while循环并开始接受所有传入的连接,并在向所有连接的套接字发送感谢消息后关闭这些连接。
客户 :
现在我们需要一个服务器可以与之交互的东西。我们可以这样对待服务器,只是为了知道我们的服务器正在工作。在终端中键入以下命令:
# start the server
$ python server.py
# keep the above terminal open
# now open another terminal and type:
$ telnet localhost 12345
如果无法识别“telnet”。在 windows 上搜索 windows 功能并打开“telnet 客户端”功能。
输出 :
# in the server.py terminal you will see
# this output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# In the telnet terminal you will get this:
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Thank you for connectingConnection closed by foreign host.
此输出表明我们的服务器正在运行。
现在对于客户端:
Python3
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
# close the connection
s.close()
- 首先,我们创建一个套接字对象。
- 然后我们在端口 12345(我们的服务器运行的端口)上连接到 localhost,最后,我们从服务器接收数据并关闭连接。
- 现在将此文件保存为 client.py 并在启动服务器脚本后从终端运行它。
# start the server:
$ python server.py
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('127.0.0.1', 52617)
# start the client:
$ python client.py
Thank you for connecting