程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Implementation of Python Network Communication Based on TCP transmission protocol

編輯:Python

1、 Basic concepts

What is network programming ?

In the network environment , How to achieve Not in the same physical location Data communication between computers in

 

If you want to ensure the smooth completion of data communication , You need to understand the following concepts first :

1.1 agreement

Data communication between processes in different computers , The data needs to be analyzed first Package or pack Before transmission . The so-called protocol refers to the data packaging format that both communication parties need to abide by .

Just like mailing goods in the real world :

  1. The commodity is equivalent to the data to be transmitted to the other party : Before transmission , The owner of the goods is required to package the goods , And fill in when packing Write the recipient's address 、 Name of receiver 、 sender address …… This is the first time to package , The packaging format followed in this packaging process is completed by the commodity packer , This layer of packaging standard can be called application layer standard or application layer protocol .
  2. The package will be received by the logistics company , Logistics companies receive packages that need to be sent all over the country every day , therefore , It needs to be inspected again , Put packages sent to the same area together , And pack again , Fill in the corresponding information according to the standard . It can be considered that the standard of the second packaging is the post office standard or post office agreement .
  3. The package packed by the post office will be sent to the relevant transportation department , The transportation department will sort and pack the packages collected from different post offices according to their destination , Then select different means of transportation for transmission , Can choose The plane 、 truck 、 train …… This time, The packaging protocol can be called transport layer protocol .

Protocol is the first operation element to ensure that data can be transmitted correctly , The protocol specification followed on the Internet is called TCP/IP agreement .

1.2 IP Address

In the network environment , You need to specify an address for each computer , This address is IP Address , Actually IP Address is a logical address , And each computer has a physical address , It's on the network card MAC Address .

IP Address and MAC The difference in address ?

  • MAC The address is equivalent to your ID number. , Is constant 、 constant .
  • IP The address is equivalent to the address where you and I are now . Some people within a year , May work in different cities , This means that there can be multiple logical addresses .

1.3 port

Multiple network software can be installed on one computer , Such as QQ、 browser 、 Network game ……

How does the operating system distinguish which software should handle multiple data from the network at the same time ?

The port is equivalent to one assigned by the operating system to each network software House plate identification symbol , It is used to correctly divert multiple data streams input from the network to the corresponding process .

When one computer sends data to another computer :

  1. First, package the data according to the protocol format
  2. In addition, you need to know the address of the other computer and the port number monitored by the corresponding process . IP+ Port number Also known as sockets , Or call   socket

It's kind of like visiting friends :

First encapsulate a gift box

Then go to visit according to the address and house number told by your friend

2、TCP Network programming implementation

TCP Is a transport layer protocol , It is a reliable connection oriented transport layer protocol .

2.1 Server side programming

Define a function for specific data interaction , Called by a child thread .

import socket # socket modular
import time # Time module
import threading # Thread module
def session(sock, addr):
print(' Welcome new %s:%s...' % addr)
sock.send(b'Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
# Decode data
if not data or data.decode('utf-8') == 'exit':
break
sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
sock.close()
print(' From %s:%s The connection is closed .' % addr)

establish socket listening object :

# establish TCP socket
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Listening port
server.bind(('127.0.0.1',1234))
server.listen(5)
print(' The server is waiting for the client to connect ……')
 Establish a service listening socket , You need to specify the  Service type :

 

while True:
# Accept a new connection :
sock, addr = s.accept()
# Create a new thread to handle TCP Connect :
t = threading.Thread(target=session, args=(sock, addr)) t.start()

When a customer is connected , Start the thread to complete the specific data processing .

2.2 Client programming

The client code is relatively simple .

import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Establishing a connection :
client.connect(('127.0.0.1', 1234))
# Receive a welcome message :
print(client.recv(1024).decode('utf-8'))
for data in [b'Rose', b'Think', b'Babala']:
# send data :
s.send(data)
print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()

test result :

Server side

client :

3 summary

Python Relevant modules are provided , Encapsulates the underlying concrete code logic , For developers , Just follow the process step by step , If you need to better understand the whole process of network communication , You need to know relevant network knowledge .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved