python Network Programming

Keywords: socket network Python Programming

Introduction to TCP/IP

(Extracted from Baidu Encyclopedia)
1. TCP/IP Protocol
The abbreviation of Transmission Control Protocol/Internet Protocol, translated into Chinese as transmission control protocol/Internet interconnection protocol, also known as network communication protocol, is the most basic protocol of the Internet and the basis of Internet Internet. It consists of IP protocol of network layer and TCP protocol of transport layer. TCP/IP defines standards for how electronic devices are connected to the Internet and how data is transmitted between them. The protocol adopts a hierarchical structure of four layers. Each layer calls the protocol provided by its next layer to fulfill its own requirements. Generally speaking, TCP is responsible for discovering transmission problems, sending out signals whenever there is a problem and requiring re-transmission until all data is safely and correctly transmitted to the destination. IP provides an address for every networking device on the Internet.

2.TCP/IP protocol is not the combination of TCP and IP, but refers to the whole TCP/IP protocol family of the Internet.
In terms of protocol layering model, TCP/IP consists of four layers: network interface layer, network layer, transport layer and application layer.
TCP/IP protocol does not fully conform to the seven-tier reference model of OSI. OSI (Open System Interconnect) is a traditional open system interconnection reference model, and is a seven-tier abstract reference model of communication protocol, in which each layer performs a specific task. The aim of this model is to make all kinds of hardware communicate with each other at the same level. These seven layers are: physical layer, data link layer (network interface layer), network layer (network layer), transport layer (transport layer), session layer, presentation layer and application layer (application layer). The TCP/IP communication protocol adopts a four-tier hierarchical structure, each layer calls the network provided by its next layer to fulfill its own needs. Because ARPANET designers focus on network interconnection, allowing communication subnetworks (network interface layer) to adopt existing or future protocols, there is no specific protocol in this layer. In fact, TCP/IP protocol can be connected to any network through network interface layer, such as X.25 switching network or IEEE802 LAN.

Note that tcp itself does not have the function of error detection caused by noise in data transmission, but it has the function of error retransmit with timeout.

II. TCP Programming

#SocketTcpServer.py 
import socket
import threading
import time
# Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 9999))
s.listen(5)
print('TCPServer is waiting for connection...')
def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'Welcome!')
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)
while True:
    # Accept a new connection:
    sock, addr = s.accept()
    # Create new threads to handle TCP connections:
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()
#SocketTcpClient.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect:
s.connect(('127.0.0.1', 9999))
# Receive welcome messages:
print(s.recv(1024).decode('utf-8'))
for data in [b'Jaber', b'Katy', b'Betty', b'huangxin']:
    # Send data:
    s.send(data)
    print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()
#server (state when not connected)
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/HomeWorkByNetwork/SocketTcpServer.py
TCPServer is waiting for connection...
#server (status after successful connection)
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/HomeWorkByNetwork/SocketTcpServer.py
TCPServer is waiting for connection...
Accept new connection from 127.0.0.1:55380...
Connection from 127.0.0.1:55380 closed.

#client
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/HomeWorkByNetwork/SocketTcpClient.py
Welcome!
Hello, Jaber!
Hello, Katy!
Hello, Betty!
Hello, huangxin!

Process finished with exit code 0

UDP Programming

#SocketUcpServer.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Binding ports:
s.bind(('127.0.0.1', 8888))
print('Bind UDP on 8888...')
while True:
    # Receiving data:
    data, addr = s.recvfrom(1024)
    print('Received from %s:%s.' % addr)
    s.sendto(b'Hello, %s!' % data, addr)
#SocketUcpClient.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for data in [b'Michael', b'Tracy', b'Sarah']:
    # Send data:
    s.sendto(data, ('127.0.0.1', 8888))
    # Receiving data:
    print(s.recv(1024).decode('utf-8'))
s.close()
#server (state when not connected)
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/HomeWorkByNetwork/SocketUdpServer.py
Bind UDP on 8888...
#server (status after successful connection)
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/HomeWorkByNetwork/SocketUdpServer.py
Bind UDP on 8888...
Received from 127.0.0.1:52492.
Received from 127.0.0.1:52492.
Received from 127.0.0.1:52492.

#client
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/HomeWorkByNetwork/SocketUdpClient.py
Hello, Michael!
Hello, Tracy!
Hello, Sarah!

Process finished with exit code 0

Posted by millwardt on Thu, 16 May 2019 04:01:19 -0700