Python socket programming
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
