Today I read the second chapter of Python's core programming, which tells about the communication of the Python socket module, with the following notes:
Sockets: 1, Af_unix af_inet socket Address: Host-port to connection-oriented sockets: A connection must be established before communication, such as using a telephone to call a friend, the primary protocol for implementing this type of connection is transmission Protocol (TCP) to create a TCP socket, and must use the sock _stream a socket-type connectionless socket: Without establishing a connection, as with a postal service, the primary protocol for implementing this type of connection is User Datagram Protocol (UDP), which creates a UDP socket, and must use SOCK_DGRAM as the type of socket The comparison between the two sockets: TCP ensures the arrival of the data, combines the messages in order, and finally passes the full message to the waiting application; UDP does not necessarily guarantee the arrival of the data, and the data is not sequential, but low maintenance costs often provide better performance. 2,
2. Create TCP Server HOST = ' PORT = 21567 Bufsiz = 1024 ADDR = (HOST, PORT) Tcpsersock = socket (af_inet, sock_stream) tcpsersock.
Bind (ADDR) Tcpsersock.listen (5) While True:print ' Waiting for connection ... ' tcpclisock, ADDR = Tcpsersock.accept () print ' ... connected from: ', addr while true:data = TCPCLISOCK.RECV (bufsiz) if not data:break tcpclisock.send (
' [%s]%s '% (CTime (), data) Tcpclisock.close () Tcpsersock.close () 3, create TCP client from socket import * from time import CTime HOST = ' localhost ' PORT = 31567 Bufsiz = 1024 ADDR = (host, PORT) Tcpclisock = socket (af_inet, sock_stream) tcpclisock.c Onnect (ADDR) while true:data = Raw_input (' > ') if not data:break tcpclisock.send (data) data = TCPCLISOCK.RECV ( Bufsiz) if not data:break print Data tcpclisock.close () 4, creating a UDP server from socket import * from time import CTime HOST = ' PORT = 21567 Bufsiz = 1024 ADDR = (HOST, PORT) Udpsersock = socket (af_inet, Sock_dgram) Udpsersock.bind (ADDR) while True:print ' Waiting For message ... ' data, addr = Udpsersock.recvfrom (bufsiz) udpsersock.sendto (' [%s]%s '% (CTime (), data), addr) print ' ... r
Ecevied fro, and returned to: ', addr udpsersock.close () 5, create UDP client from socket import * HOST = ' localhost ' PORT = 21567 Bufsiz = 1024 ADDR = (HOST, PORT) Udpclisock = socket (af_inet, sock_dgram) while true:data = Raw_input (' > ') if no
T data:break udpclisock.sendto (data, ADDR) data, ADDR = Udpclisock.recvfrom (bufsiz) if not data:break print data Udpclisock.close ()