Af_inet:ipv4
Af_inet6:ipv6
Socket Type:
Sock_stream:tcp
Sock_dgram:udp
Create a TCP socket, or you can create a TCP socket by default without passing parameters
Tcpsocket = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
The following is a simple TCP server-side and client-based implementation of Python3
TCP sends and receives data using send, recv
Service side:
1 ImportSocket2 3HOST ="127.0.0.1"4PORT = 99995Buffsize = 10246ADDR =(HOST, PORT)7 8Tcpsocket =Socket.socket (socket.af_inet, socket. SOCK_STREAM)9 Ten Tcpsocket.bind (ADDR) One ATcpsocket.listen (5) - - whileTrue: the Print("watting clien Connection ...") -Tcpcliensock, addr =tcpsocket.accept () - Print("Connected from:", addr) - whileTrue: +data =tcpcliensock.recv (buffsize) - if notData: + Break A Print("I have received data:", data) atSendData ="Hello, I have received your date:%s"%Data -Tcpcliensock.send (Bytes (SendData, encoding="Utf-8")) - tcpcliensock.close () -Tcpsocket.close ()
Client:
1 ImportSocket2 3HOST ="127.0.0.1"4PORT = 99995Buffsize = 10246ADDR =(HOST, PORT)7 8Tcpclientsock =Socket.socket ()9R =Tcpclientsock.connect (ADDR)Ten Print(R) One A whileTrue: -data = input (">>") - ifdata = ="Q" ordata = ="quit": the Break -Tcpclientsock.send (bytes (data, encoding="Utf-8")) -RecvData =tcpclientsock.recv (buffsize) - if notRecvData: + Break - Print(RecvData) +Tcpclientsock.close ()
Next is a simple UDP server and client implementation
UDP sends and receives data using SendTo, Recvfrom
UDP Server:
1 ImportSocket2 3HOST ="127.0.0.1"4PORT = 99995Buffsize = 10246ADDR =(HOST, PORT)7 #after the UDP server creates the socket, it only needs to bind the IP and port number, waiting to receive the data8 #no need for listen and accept9Udpsocket =Socket.socket (socket.af_inet, socket. SOCK_DGRAM)Ten Udpsocket.bind (ADDR) One A whileTrue: - Print("watting Message ...") -data, addr = Udpsocket.recvfrom (buffsize)#will return the sender's address theSendData ="Hello, I have recv your date:%s"%Data -Udpsocket.sendto (Bytes (SendData, encoding="Utf-8"), addr) - Print("Receive message%s from%s"%(data, addr)) -Udpsocket.close ()
UDP client:
1 ImportSocket2 3HOST ="127.0.0.1" #' localhost ' can also4PORT = 99995Buffsize = 10246ADDR =(HOST, PORT)7 #create sockets to send data without a connect connection8Udpclientsock =Socket.socket (socket.af_inet, socket. SOCK_DGRAM)9 Ten whileTrue: Onedata = input (">>") A ifdata = ="Q" ordata = ="quit": - Break -Udpclientsock.sendto (bytes (data, encoding="Utf-8"), ADDR) theRecvData, addr =Udpclientsock.recvfrom (buffsize) - if notRecvData: - Break - Print(RecvData) +Udpclientsock.close ()
Python Network Programming Note I