search
HomeBackend DevelopmentPython TutorialPython network programming

Python network programming

Nov 01, 2016 pm 01:18 PM
python

Understand Socket

Socket is also commonly called "socket", which is used to describe IP addresses and ports. It is the handle of a communication chain. Applications usually make requests to the network or respond to network requests through "sockets".

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is "everything is a file". For files, use the [Open] [Read and Write] [Close] mode to operate. Socket is an implementation of this mode. Socket is a special file. Some socket functions are operations on it (read/write IO, open, close). The difference between socket and file:

file module is for [Open] [Read and Write] [Close] a specified file

The socket module is for server-side and client-side Sockets to [Open] [Read and Write] [Close]

Python network programming


ython (version 3.5 ) To achieve the simplest socket communication

#!/usr/bin/env python
# coding=utf-8
# Author:Majh

import socket

ip_port = ('127.0.0.1', 9999)
sk = socket.socket()

sk.connect(ip_port)
send_data = input('>>').strip()
sk.send(bytes(send_data, encoding='utf-8'))
recv_data = sk.recv(1024)
print(str(recv_data, encoding='utf-8'))
sk.close()

客户端代码
#!/usr/bin/env python
# coding=utf-8
# Author:Majh

import socket

sk = socket.socket()
ip_port = ('127.0.0.1', 9999)

sk.bind(ip_port)
print('sk.bind......')
sk.listen(5)
print('sk.listen......')
conn, addr = sk.accept()
print('conn:', conn)
print('addr:', addr)

read_data = conn.recv(1024)
print('read_data', read_data)
read_data = read_data.upper()

conn.send(read_data)
conn.close()

服务器端代码

socket keyword parameters:

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)

Parameter 1: Address cluster

 socket.AF_INET IPv4 (default)

  socket.AF_INET6 IPv6


  socket.AF_UNIX can only be used for inter-process communication in a single Unix system

Parameter 2: Type

  socket.SOCK_STREAM Streaming socket, for TCP (default)

  socket.SOCK_DGRAM  Datagram socket , for UDP


  socket.SOCK_RAW raw socket. Ordinary sockets cannot process network messages such as ICMP and IGMP, but SOCK_RAW can. Secondly, SOCK_RAW can also process special IPv4 messages. In addition, using raw sockets word, the IP header can be constructed by the user via the IP_HDRINCL socket option.

 Socket.SOCK_RDM is a reliable form of UDP, which guarantees the delivery of datagrams but does not guarantee the order. SOCK_RAM is used to provide low-level access to the original protocol and is used when certain special operations need to be performed, such as sending ICMP messages. SOCK_RAM is usually restricted to programs run by power users or administrators.

  socket.SOCK_SEQPACKET Reliable continuous packet service

Parameter three: Protocol

 0  (Default) The protocol related to a specific address family. If it is 0, the system will automatically select it based on the address format and socket category. A suitable protocol

sk.bind(address)

 s.bind(address) binds the socket to the address. The format of address depends on the address family. Under AF_INET, the address is expressed in the form of a tuple (host, port).

sk.listen(backlog)

Start listening for incoming connections. The backlog specifies the maximum number of connections that can be pending before the connection is rejected.

Backlog equals 5, indicating that the kernel has received the connection request, but the server has not yet called accept for processing. The maximum number of connections is 5

This value cannot be infinite because the connection queue must be maintained in the kernel


sk.setblocking( bool)

 Whether to block (default True), if set to False, an error will be reported if there is no data during accept and recv.

sk.accept()

  Accept the connection and return (conn, address), where conn is a new socket object that can be used to receive and send data. address is the address to connect to the client.

 Receive the connection from the TCP client (blocking) and wait for the connection to arrive

sk.connect(address)

 Connect to the socket at address. Generally, the format of address is a tuple (hostname, port). If a connection error occurs, a socket.error error is returned.

sk.connect_ex(address)

  Same as above, except there will be a return value, 0 is returned when the connection is successful, and the code is returned when the connection fails, for example: 10061

sk.close()

 Close the socket

sk .recv(bufsize[,flag])

 Accepts socket data. The data is returned as a string, and bufsize specifies the maximum number that can be received. flag provides additional information about the message and can usually be ignored.

sk.recvfrom(bufsize[.flag])

  Similar to recv(), but the return value is (data, address). Where data is a string containing the received data, and address is the socket address to which the data is sent.

sk.send(string[,flag])

  Send the data in string to the connected socket. The return value is the number of bytes to send, which may be less than the string's byte size. That is: all specified content may not be sent.

sk.sendall(string[,flag])

  Sends the data in string to the connected socket, but attempts to send all data before returning. Returns None on success, throws an exception on failure.

Internally, all content is sent out by calling send recursively.

sk.sendto(string[,flag],address)

  Send data to the socket, address is a tuple in the form of (ipaddr, port), specifying the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.

sk.settimeout(timeout)

Set the timeout period for socket operations. timeout is a floating point number in seconds. A value of None means there is no timeout period. Generally, the timeout period should be set when the socket is first created, because they may be used for connection operations (such as client connections waiting up to 5s)

sk.getpeername()

  Returns the remote address of the connected socket. The return value is usually a tuple (ipaddr, port).

sk.getsockname()

  Returns the socket’s own address. Usually a tuple (ipaddr,port)


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools