博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python编程示例_Python套接字编程–服务器,客户端示例
阅读量:2535 次
发布时间:2019-05-11

本文共 7226 字,大约阅读时间需要 24 分钟。

python编程示例

Good Day Learners! In our previous tutorial, we discussed about module. Today we will look into python socket programming example. We will create python socket server and client applications.

美好的一天学习者! 在上一教程中,我们讨论了单元测试模块。 今天,我们将研究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.

因此,我们将设计服务器和客户端模型,以使每个模型都可以与它们通信。 可以这样考虑这些步骤。

  1. Python socket server program executes at first and wait for any request

    Python套接字服务器程序首先执行并等待任何请求
  2. Python socket client program will initiate the conversation at first.

    Python套接字客户端程序将首先启动对话。
  3. Then server program will response accordingly to client requests.

    然后,服务器程序将相应地响应客户端请求。
  4. 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 socketdef 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 connectionif __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 and break statement. is used to run the server program indefinitely and keep waiting for client request.

因此,我们的python套接字服务器在端口5000上运行,它将等待客户端请求。 如果要在关闭客户端连接时不退出服务器,只需删除和break语句。 用于无限期地运行服务器程序并持续等待客户端请求。

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 socketdef 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 connectionif __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 -> Hellofrom connected user: How are you? -> Goodfrom connected user: Awesome! -> Ok then, bye!pankaj$
pankaj$ python3.6 socket_client.py  -> HiReceived from server: Hello -> How are you?Received from server: Good -> Awesome!Received from server: Ok then, bye! -> Byepankaj$

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:

参考:

翻译自:

python编程示例

转载地址:http://pyqzd.baihongyu.com/

你可能感兴趣的文章
小D课堂 - 零基础入门SpringBoot2.X到实战_第1节零基础快速入门SpringBoot2.0_5、SpringBoot2.x的依赖默认Maven版本...
查看>>
阶段3 3.SpringMVC·_07.SSM整合案例_08.ssm整合之Spring整合MyBatis框架
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_9、SpringBoot基础HTTP其他提交方法请求实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_12、SpringBoot2.x文件上传实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_19、SpringBoot个性化启动banner设置debug日志...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_20、SpringBoot2.x配置全局异常实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第5节 SpringBoot部署war项目到tomcat9和启动原理讲解_23、SpringBoot2.x启动原理概述...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_21、SpringBoot2.x配置全局异常返回自定义页面...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_32..SpringBoot2.x持久化数据方式介绍...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_34、SpringBoot整合Mybatis实操和打印SQL语句...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第8节 数据库操作之整合Mybaties和事务讲解_35、事务介绍和常见的隔离级别,传播行为...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_40、Redis工具类封装讲解和实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_37、分布式缓存Redis介绍...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_42、SpringBoot常用定时任务配置实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_39、SpringBoot2.x整合redis实战讲解...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第14节 高级篇幅之SpringBoot多环境配置_59、SpringBoot多环境配置介绍和项目实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_41、SpringBoot定时任务schedule讲解...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_43、SpringBoot2.x异步任务实战(核心知识)...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_1_01课程简介
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第11节 Logback日志框架介绍和SpringBoot整合实战_45、SpringBoot2.x日志讲解和Logback配置实战...
查看>>