This article mainly introduces the relevant information of Python network programming in detail. Python socket programming has certain reference value. Interested friends can refer to it
Python provides two level of access to network services.
The low-level network service supports basic Socket, which provides the standard BSD Sockets API and can access all methods of the underlying operating system Socket interface.
High-level network service module SocketServer, which provides server center classes that can simplify the development of network servers.
What is Socket?
Socket is also called "socket". Applications usually send requests to or respond to the network through "socket" Requests enable communication between hosts or between processes on a computer.
socket() function
In Python, we use the socket() function to create a socket. The syntax format is as follows:
socket.socket ([family[, type[, proto]]])
Parameters
family: The socket family can be AF_UNIX or AF_INET
type: The socket type can be Depending on whether it is connection-oriented or non-connection, it is divided into SOCK_STREAM or SOCK_DGRAM
protocol: Generally, if not filled in, the default is 0.
socket realizes simple communication between the server and the client (simulating ssh Some functions and automatic responses)
Simple program example on the server side:
#!/usr/bin/env python #coding:utf-8 ''' file:server.py date:9/8/17 3:43 PM author:lockey email:lockey@123.com desc:socket编程服务器端,python3.6.2 ''' import re import socket,time,os s = socket.socket() # 创建 socket 对象 host = '127.0.0.1'#socket.gethostname() # 获取本地主机名 port = 9999 # 设置端口 s.bind((host, port)) # 绑定端口 s.listen(5) # 等待客户端连接 while True: conn, addr = s.accept() # 建立客户端连接。 print('conneted address:'.decode('utf-8'), addr)#显示连接到服务器的客户端的地址 while True: data = conn.recv(1024) #接收到的客户端的请求或者返回 if not data: #当返回信息为空或者请求为空时断开客户端连接 print('Connection closed!') break; data = data.decode('utf-8') #以下前三个条件都是设置的自动检测应答,最后一个是根据输入的内容进行的命令执行,并将结果返回给客户端 if re.findall(r'who',data): reply = 'I am lockey'.encode('utf-8') elif re.findall(r'gender',data): reply = 'A boy'.encode('utf-8') elif re.findall(r'age',data): reply = '23'.encode('utf-8') else: print('execute com:',data) cmd_res = os.popen(data).read() if not cmd_res: #对于命令的执行如果没有返回值的话就给客户端发送一条信息 conn.send('No response'.encode('utf-8')) continue reply = cmd_res.encode('utf-8') conn.send(reply) #将结果发送给客户端
Simple implementation on the client side:
#!/usr/bin/env python #coding:utf-8 ''' file:client.py date:9/8/17 3:43 PM author:lockey email:lockey@123.com desc:socket编程客户端,python3.6.2 ''' import socket,time # 导入 socket 模块 s = socket.socket() # 创建 socket 对象 host = '127.0.0.1'#socket.gethostname() # 获取本地主机名 port = 9999 # 设置端口好 s.connect((host, port)) while True: cmd = input("lockey#") #用户输入 if len(cmd) == 0:continue #如果用户未输入内容则继续下一次输入 s.send(cmd.encode('utf-8')) #将用户输入的内容发送给客户端等待结果 result = s.recv(1024) if not result: #如果服务端没有返回结果则继续下一次输入 continue print(result.decode('utf-8')) #如果服务端有返回则打印结果 s.close() #用户终止程序时关闭连接
Server-side running results
Client-side running screenshot
The above is the detailed content of Python socket programming. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software