Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic knowledge of python network programming

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What are the knowledge points of this article "what are the basic knowledge of python network programming?" most people do not understand, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article, "what are the basic knowledge of python network programming?"

one。 What is network programming?

Network programming involves some basic computer knowledge, and it is also related to your computer system. Mac os/Linux and windows are different, because I use windows, so all of the following are applicable to the windows operating system, and the character coding windows and mac os are also different. Here, what we achieve is that the client receives what the server sends. After that, there will be remote commands to simulate ssh, as well as sticky package problems, and finally you can download files.

Network programming also involves an important part of theoretical knowledge, including what is the network and the more important five-layer protocols. As far as I understand it, these things are professional to tell you that you are supposed to receive some files on your computer. How are these things transmitted, and how does your computer receive them? So here is nothing more than an interaction between your computer, that is, the client, and the party that transfers the file, that is, the service point. I suggest you listen to all these (I think it will be a little inadequate in terms of personal ability), but the big aspects are inseparable from an interaction.

II. Socket

As we all know, a large part of the powerful function of python is that it has a powerful third-party external library, socket, also known as sockets, professional explanation is that applications usually send requests to the network or respond to network requests through "sockets", so that processes between hosts or on a computer can communicate, and then through socket this library can achieve the interaction between the client and the server that I mentioned earlier.

Basic syntax of 1.socket

Socket (family,type, [protocol])

There are three kinds of family.

Socket.AF_UNIX can only be used for interprocess communication in a single Unix system.

Network communication between socket.AF_INET servers

Socket.AF_INET6 IPv6

There are also three kinds of type

Socket.SOCK_STREAM streaming socket, select this parameter when using TCP

Socket.SOCK_DGRAM Datagram socket, which is selected when using UDP

Socket.SOCK_RAW raw sockets, ordinary sockets can not handle ICMP, IGMP and other network messages, but SOCK_RAW can; secondly, SOCK_RAW can also deal with special IPv4 messages; in addition, using raw sockets, users can construct IP headers through the IP_HDRINCL socket option.

On the other hand, protocol indicates the type of protocol to be received, which is usually 0 or left empty, which is basically unwritten.

two。 Some functions related to socket server functions

Address generally refers to the ip address on your computer, that is, when you open the Windows command prompt, you enter the ipconfig command after you connect to the Internet, and the IPV4 in it.

S.bind (address) binds the socket to the address, that is, in the client, you have to bind your program to an ip and port in order to interact.

The maximum number of connections that the s.listen (backlog) operating system can suspend. That is, your server can send data to at most several clients.

S.accept () accepts a TCP connection and returns (conn,address), where conn is a new socket object that can be used to receive and send data. Address is the address where the client is connected.

Client function

S.connect (address) connects to the socket at the client address

S.recv (bufsize) accepts data from TCP sockets. Data is returned as a string, and bufsize specifies the maximum amount of data to receive.

Common function

S.send (string)

Send TCP data. Sends the data in the string to the connected socket. The return value is the number of bytes to be sent, which may be less than the byte size of string.

S.sendall (string)

Send TCP data in full. Sends data from string to the connected socket, but attempts to send all data before returning. None is returned for success, and an exception is thrown for failure.

S.recvfrom (bufsize)

Accept data from UDP sockets. Similar to recv (), but the return value is (data,address). Where data is the string containing the received data and address is the socket address where the data is sent.

S.sendto (string,address)

Send UDP data. Sends the data to the socket, where address is a tuple in the form (ipaddr,port) that specifies the remote address. The return value is the number of bytes sent.

S.close ()

Close the socket.

three。 Program requirement

Since it is a kind of interaction, making a phone call and receiving a phone call in life can also be understood as an interaction, making a call can be understood as sending data, and receiving a phone call can be understood as receiving data, so there are servers and clients. Here we interact with such a scenario.

Server-side analysis

If you want to send data, you first have to have a mobile phone and then introduce socket to interact, and then you need to perform a series of binding operations, that is, you need the above functions to implement. First, after you simulate a mobile phone on the client side and introduce socket, you need to bind, boot, wait for phone links, send and receive messages, hang up and other functions.

Note:

1. During the binding operation, you need to enter your local ip address after networking, that is, you open the command prompt and enter the IPV4 address of the ipconifg command.

two。 After binding your address, it will be followed by a port number. This port number is arbitrary, but sometimes it will be occupied. If it is occupied, just change the following.

3. There is also a upper function in the manipulation message, which sends the data sent by the client to the client in uppercase.

4. To use accept on the client side is to accept the TCP connection and return (conn,address)

-- server-- import socket#1. Buy a phone phone = socket.socket (socket.AF_INET,socket.SOCK_STREAM) # print (phone) # test your phone # 2. Card binding mobile phone card phone.bind (("192.168.2.18", 3234)) # 3. Boot phone.listen (5) # 5 represents the maximum number of pending connections # 4. Wait for the phone link print ("starting") conn,client_add = phone.accept () # 5. Sending and receiving messages data=conn.recv (1024) # 1024 represents the maximum number of received data in bitsprint ("client data", data) conn.send (data.upper ()) # 6. Hang up the phone conn.close () # 7. Analysis of phone.close () client when shutdown

After the server analysis, the client and the server correspond to each other one by one. Here, the client sends a lowercase hello to the server, and the server returns an uppercase HELLO to the client.

Client-- import socket#1. Buy mobile phone phone = socket.socket (socket.AF_INET,socket.SOCK_STREAM) # print (phone) # 2. Dial phone.connect (("192.168.2.18", 3234)) # 3. Send and receive messages phone.send ("hells". Encode ("utf")) data=phone.recv (1024) print (data) phone.close () four. Code upgrade plus communication loop

As we can see from the above code, our implementation is too simple. We just let it send and receive messages. How do we loop this program between the client and the server and send and receive what you want? this is what we can add input and loop.

-import socket phone = socket.socket (socket.AF_INET,socket.SOCK_STREAM) # print (phone) phone.bind (("172.20.10.4", 3234)) phone.listen (5) print ("starting") conn Client_add = phone.accept () print (client_add) while True: data=conn.recv (1024) print ("client data" Data) conn.send (data.upper ()) conn.close () phone.close ()-client-import socket phone = socket.socket (socket.AF_INET,socket.SOCK_STREAM) # print (phone) phone.connect (("172.20.10.4") 3234) while True: msg = input (">:"). Strip () phone.send (msg.encode ("utf-8")) data=phone.recv (1024) print (data) phone.close ()

As you can see, we just add the loop input function in the client side, how to add the loop in the server side, so that we can realize a kind of loop input.

Plus connection loops and refinement

Our above programs are all one client corresponding to one server, but the server should be able to send and receive data corresponding to multiple clients. What we mainly modify is the server code, and the client code should not change much, except that the client side should add a judgment to determine whether there is any data sent.

1. We didn't learn concurrent programming, so our code is implemented in a loop, that is, after your server accepts data from one client, you can continue to receive data from another client.

two。 In addition, we have added a line of code to determine whether your port is occupied so that errors can be reduced.

3. After I add a client, we will have another question, that is, whether we need the data transmitted by another client, or whether our multiple clients have sent data, so we need a try and except to judge first.

-- import socket phone = socket.socket (socket.AF_INET,socket.SOCK_STREAM) phone.setsockopt (socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # determine whether the interface is occupied by phone.bind (("172.20.10.4") 3234) phone.listen (5) print ("starting") while True: # without learning concurrent programming and unable to execute the code, return to this to continue execution So use a loop to solve conn,client_add = phone.accept () print (client_add) while True: try: data=conn.recv (1024) if not data:break print ("client data") Data) conn.send (data.upper ()) except ConnectionResetError: break conn.close () phone.close ()-client 1-import socket phone = socket.socket (socket.AF_INET,socket.SOCK_STREAM) phone.connect (("172.20.10.4") 3234) while True: msg = input (">:"). Strip () if not msg: continue # if left empty, continue to loop phone.send (msg.encode ("utf-8")) # print ("if send none") data=phone.recv (1024) print (data) # print (data.decode ("utf-8") phone.close ()- -client 2-import socket phone = socket.socket (socket.AF_INET Socket.SOCK_STREAM) phone.connect ("172.20.10.4" 3234) while True: msg = input (">:"). Strip () if not msg: continue # if you enter blank, continue to loop phone.send (msg.encode ("utf-8")) # print ("if send none") data=phone.recv (1024) print (data) # print (data.decode ("utf-8") phone.close () above is about the network programming base of python. What is the content of this article? I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report