Python provides two basic socket modules.
The first one is the Socket, which provides the standard BSD Sockets API.
The second is Socketserver, which provides a server-centric class that simplifies the development of Web servers.
Socket Type Socket Format:
Socket (Family,type[,protocal])
Creates a socket with the given address family, socket type, protocol number (default = 0, not typically written).
Address family:
Socket Type |
Description |
Socket.af_unix |
Single UNIX inter-process communication |
Socket.af_inet |
Communication between servers |
Scoket.af_inet6 |
IPV6 use |
Socket Type:
Socket Type |
Description |
Socket. Sock_stream |
Streaming for TCP |
Socket. Sock_dgram |
Packet packet for UDP |
Scoket. Sock_raw |
The original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, using the original socket, you can use the IP_HDRINCL socket option by the user constructs the IP header. |
Socket. Sock_seqpacket |
Robust, continuous packet format |
The server and client cannot send lists, tuples, dictionaries directly. Requires a string of repr (data).
Example of creating a TCP server:
Ideas:
1. Create a Socket object
Tcpsersock=socket (Af_inet,sock_stream) #创服务器套接字
2, bound host and port, should be a tuple
Tcpsersock.bind (ADDR) #套接字与地址绑定
3. Monitoring
Tcpsersock.listen (5) #监听连接, the maximum number of incoming connection requests
4. Wait for the connection
CONN,ADDR = tcpsersock.accept () addr is an IP address, conn is the data object sent to
5. Acceptance of data
data = CONN.RECV () needs to be manipulated with the Conn object
6. Send data
Conn.send (data) or Conn.sendall (data)
7. Close socket
Conn.close ()
Tcpsersock.close ()
* The decode and encode used here are Python3 need bytes data when creating a socket
When sending, need to use Encode (), peer received, need to use decode ()
*
#创建TCP服务器from Socket import *from time import Ctimeimport subprocesshost= ' port=21567bufsiz=1024addr= (HOST , PORT) Tcpsersock=socket (Af_inet,sock_stream) #创服务器套接字tcpSerSock. bind (ADDR) #套接字与地址绑定tcpSerSock. Listen (5) #监听连接, The maximum number of incoming connection requests while the True:print (' Waiting for connection ... ') tcpclisock,addr =tcpsersock.accept () print (' ... connected From: ', addr, and True:data =tcpclisock.recv (Bufsiz). Decode () if not data:continue p Rint (' command= ', data) Status,result = subprocess.getstatusoutput (data) if result.strip () = = 0:TC Pclisock.send (' [%s] Create a dir or file finish! '% (CTime ())). Encode ()) Else:tcpCliSock.send ((' [%s]%s '% (CTime (), result)). Encode ()) Tcpclisock.clos E () tcpsersock.close ()
Example of a TCP client:
Ideas:
1. Create a Socket object
Tcpclisock=socket (Af_inet,sock_stream) #创服务器套接字
2, connect the host, should be a tuple
Tcpclisock.connect (ADDR) #套接字与地址绑定
3. Send data
Tcpclisock.send (data) or Sendall (data)
4. Receive data
TCPCLISOCK.RECV (1024)
5. Close
Tcpclisock.close ()
from socket import *HOST = ‘localhost‘ # or ‘localhost‘PORT = 21567BUFSIZ = 1024ADDR=(HOST,PORT)tcpCliSock = socket(AF_INET,SOCK_STREAM)tcpCliSock.connect(ADDR)while True: data = input(‘> ‘) #print(‘data=‘,data); if not data: break tcpCliSock.send(data.encode()) data = tcpCliSock.recv(BUFSIZ).decode() if not data: break print(data)tcpCliSock.close()
Create a UDP server
The UDP protocol does not need to establish a connection in advance to send data directly to each other.
UDP Server-side example:
Ideas:
1. Create socket sockets
s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
2. Binding
Host= ("", 8000)
S.bind (host)
3. Accept the connection
S.recvfrom (1024)
4. Send data
S.sendto (DATA,ADDR) The second parameter is a client IP
5. Close
S.close ()
import sockets = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)host=("",8000)s.bind(host)while True: data,address = s.recvfrom(1024) print(data.decode(),address) senddata = "this is a udp server" s.sendto(senddata.encode(),address)c.close()
Example of a UDP client:
1. Create sockets
s = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
2. Connection
host= ("127.0.0.1", 8000)
S.connect (host)
3. Send data
S.send (data)
4. Receive data
S.RECV (1024)
5. Close
import sockets = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)host=("127.0.0.1",8000)s.connect(host)while True: message = input("message:") s.send(message.encode()) data = s.recv(1024) print(data.decode())sl.close()
Python socket programming