Socket is an abstract concept of network programming, usually we use a socket to indicate "open a network link", and open a socket needs to know the destination computer's IP address and port number, and then specify the protocol type. Python provides two levels of network service
- 1. Low-level network services support the basic socket, which provides the standard BSD Sockets API, access to the underlying operating system socket interface of all methods
- 2. High-level Network Service Module socket server, which provides a server-centric class that simplifies the development of network servers
Socket () function, in Python we use the socket function to create a socket, syntax format such as
TCP Programming
- Network programming consists of two parts: the server and the client, TCP is a connection-oriented communication mode, the active connection called the client, the passive response called the server.
- Create a server 5 step:
- 1 Create socket, bind socket to local IP
- 2 start listening connection
- 3 Enter a loop and continue to accept client connection requests
Li>4 receive incoming data, and send to each other
- 5 transfer complete, close socket
#coding: utf-8# Create TCP Server port import socketimport threadingimport timedef dealclient (sock, addr): #第四步: Receive incoming data, Concurrent Send data print (' Accept new connection from%s:%s ... '% addr) sock.send (b ' hello,i am server! ') While true:data = Sock.recv (1024x768) time.sleep (1) If not data or Data.decode (' utf-8 ') = = ' exit ': Break print '-->>%s! '% data.decode (' utf-8 ') sock.send ((' loop_msg:%s! '% data.decode (' Utf-8 ')). Encode (' Utf-8 ')) #第五步: Close socket Sock.close () print (' Connection from%s:%s closed. '% addr ') if __name__== "__main__": #第一步: Create a Socket # socket-bound IP based on the IPV4 and TCP protocol (127.0.0.1 is native IP) with the port s = socket.socket (socket.af_inet, socket. Sock_stream) S.bind ((' 127.0.0.1 ', 9999)) #第二步: Listening connection S.listen (5) print (' Waiting for connection ... ') while Tru E: # Step three: Accept a new connection: sock, addr = s.accept () # Create a new thread to handle the TCP connection: T = Threading. Thread (Target=dealclient, args= (sock, addr)) T.start ()
Socket. Sock_stream for TCP
- Then write the client, 3 steps:
- 1 creating sockets, connecting remote addresses
- 2 Send data and receive data after connection
- 3 transfer complete, close socket
#coding:utf-8import socket#初始化Sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#连接目标的ip和端口s.connect((‘127.0.0.1‘, 9999))# 接收消息print(‘-->>‘+s.recv(1024).decode(‘utf-8‘))# 发送消息s.send(b‘Hello,I am a client‘)print(‘-->>‘+s.recv(1024).decode(‘utf-8‘))s.send(b‘exit‘)#关闭套接字s.close()
Run:
C:\Python27\python.exe F:/python_scrapy/python_study/TCP_client.py-->>Hello,I am server!-->>Loop_Msg: Hello,I am a client!Process finished with exit code 0
UDP programming
#coding:utf-8import socket#创建Socket,绑定指定的ip和端口#SOCK_DGRAM指定了这个Socket的类型是UDP。绑定端口和TCP一样。s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.bind((‘127.0.0.1‘, 9999))print(‘Bind UDP on 9999...‘)while True: # 直接发送数据和接收数据 data, addr = s.recvfrom(1024) print(‘Received from %s:%s.‘ % addr) s.sendto(b‘Hello, %s!‘ % data, addr)
- 客户端:
#coding:utf-8import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)for data in [b‘Hello‘, b‘World‘]: # 发送数据: s.sendto(data, (‘127.0.0.1‘, 9999)) # 接收数据: print(s.recv(1024).decode(‘utf-8‘))s.close()
Socket. Sock_dgram for UDP
Python network programming (Socket, TCP, UDP)