python编程示例
Good Day Learners! In our previous tutorial, we discussed about Python unittest module. Today we will look into python socket programming example. We will create python socket server and client applications.
美好的一天学习者! 在上一教程中,我们讨论了Python单元测试模块。 今天,我们将研究python套接字编程示例。 我们将创建python套接字服务器和客户端应用程序。
Python套接字编程 (Python Socket Programming)
To understand python socket programming, we need to know about three interesting topics – Socket Server, Socket Client and Socket.
要了解python套接字编程,我们需要了解三个有趣的主题- 套接字服务器 , 套接字客户端和套接字 。
So, what is a server? Well, a server is a software that waits for client requests and serves or processes them accordingly.
那么,什么是服务器? 嗯,服务器是一种等待客户端请求并相应地服务或处理它们的软件。
On the other hand, a client is requester of this service. A client program request for some resources to the server and server responds to that request.
另一方面,客户是该服务的请求者。 客户端程序向服务器请求一些资源,服务器响应该请求。
Socket is the endpoint of a bidirectional communications channel between server and client. Sockets may communicate within a process, between processes on the same machine, or between processes on different machines. For any communication with a remote program, we have to connect through a socket port.
套接字是服务器和客户端之间的双向通信通道的端点。 套接字可以在一个进程内,同一机器上的进程之间或不同机器上的进程之间进行通信。 对于与远程程序的任何通信,我们必须通过套接字端口进行连接。
The main objective of this socket programming tutorial is to get introduce you how socket server and client communicate with each other. You will also learn how to write python socket server program.
本套接字编程教程的主要目的是向您介绍套接字服务器与客户端之间如何通信。 您还将学习如何编写python套接字服务器程序。
Python套接字示例 (Python Socket Example)
We have said earlier that a socket client requests for some resources to the socket server and the server responds to that request.
前面我们已经说过,套接字客户端向套接字服务器请求一些资源,并且服务器响应该请求。
So we will design both server and client model so that each can communicate with them. The steps can be considered like this.
因此,我们将设计服务器和客户端模型,以使每个模型都可以与它们通信。 可以这样考虑这些步骤。
- Python socket server program executes at first and wait for any request Python套接字服务器程序首先执行并等待任何请求
- Python socket client program will initiate the conversation at first. Python套接字客户端程序将首先启动对话。
- Then server program will response accordingly to client requests. 然后,服务器程序将相应地响应客户端请求。
- Client program will terminate if user enters “bye” message. Server program will also terminate when client program terminates, this is optional and we can keep server program running indefinitely or terminate with some specific command in client request. 如果用户输入“再见”消息,则客户端程序将终止。 服务器程序也将在客户端程序终止时终止,这是可选的,我们可以使服务器程序无限期运行或在客户端请求中使用某些特定命令终止。
Python套接字服务器 (Python Socket Server)
We will save python socket server program as socket_server.py
. To use python socket connection, we need to import socket module.
我们将python套接字服务器程序另存为socket_server.py
。 要使用python套接字连接,我们需要导入套接字模块。
Then, sequentially we need to perform some task to establish connection between server and client.
然后,我们需要依次执行一些任务以建立服务器与客户端之间的连接。
We can obtain host address by using socket.gethostname()
function. It is recommended to user port address above 1024 because port number lesser than 1024 are reserved for standard internet protocol.
我们可以使用socket.gethostname()
函数获取主机地址。 推荐使用大于1024的用户端口地址,因为小于1024的端口号是为标准Internet协议保留的。
See the below python socket server example code, the comments will help you to understand the code.
请参阅下面的python套接字服务器示例代码,这些注释将帮助您理解代码。
import socket
def server_program():
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
# if data is not received break
break
print("from connected user: " + str(data))
data = input(' -> ')
conn.send(data.encode()) # send data to the client
conn.close() # close the connection
if __name__ == '__main__':
server_program()
So our python socket server is running on port 5000 and it will wait for client request. If you want server to not quit when client connection is closed, just remove the if condition and break statement. Python while loop is used to run the server program indefinitely and keep waiting for client request.
因此,我们的python套接字服务器在端口5000上运行,它将等待客户端请求。 如果要在关闭客户端连接时不退出服务器,只需删除if条件和break语句。 Python while循环用于无限期地运行服务器程序并持续等待客户端请求。
Python套接字客户端 (Python Socket Client)
We will save python socket client program as socket_client.py
. This program is similar to the server program, except binding.
我们将python套接字客户端程序另存为socket_client.py
。 除了绑定外,该程序与服务器程序类似。
The main difference between server and client program is, in server program, it needs to bind host address and port address together.
服务器程序和客户端程序之间的主要区别在于,在服务器程序中,它需要将主机地址和端口地址绑定在一起。
See the below python socket client example code, the comment will help you to understand the code.
请参阅下面的python套接字客户端示例代码,该注释将帮助您理解代码。
import socket
def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
message = input(" -> ") # take input
while message.lower().strip() != 'bye':
client_socket.send(message.encode()) # send message
data = client_socket.recv(1024).decode() # receive response
print('Received from server: ' + data) # show in terminal
message = input(" -> ") # again take input
client_socket.close() # close the connection
if __name__ == '__main__':
client_program()
Python套接字编程输出 (Python Socket Programming Output)
To see the output, first run the socket server program. Then run the socket client program. After that, write something from client program. Then again write reply from server program. At last, write bye from client program to terminate both program. Below short video will show how it worked on my test run of socket server and client example programs.
要查看输出,请首先运行套接字服务器程序。 然后运行套接字客户端程序。 之后,从客户端程序中编写一些内容。 然后再次写入服务器程序的回复。 最后,从客户端程序写再见以终止两个程序。 下面的短片将显示它如何在我的套接字服务器和客户端示例程序测试运行中工作。
pankaj$ python3.6 socket_server.py
Connection from: ('127.0.0.1', 57822)
from connected user: Hi
-> Hello
from connected user: How are you?
-> Good
from connected user: Awesome!
-> Ok then, bye!
pankaj$
pankaj$ python3.6 socket_client.py
-> Hi
Received from server: Hello
-> How are you?
Received from server: Good
-> Awesome!
Received from server: Ok then, bye!
-> Bye
pankaj$
Notice that socket server is running on port 5000 but client also requires a socket port to connect to the server. This port is assigned randomly by client connect call. In this case, it’s 57822.
请注意,套接字服务器在端口5000上运行,但是客户端也需要套接字端口才能连接到服务器。 此端口由客户端连接调用随机分配。 在这种情况下,它是57822。
So, that’s all for Python socket programming, python socket server and socket client example programs.
因此,Python套接字编程,Python套接字服务器和套接字客户端示例程序就这些了。
Reference: Official Documentation
参考: 官方文档
翻译自: https://www.journaldev.com/15906/python-socket-programming-server-client
python编程示例