Python Socket Programming
0x00 For Server
Firstly , you should start a TCP/IP socket.So,what’s the Socket?
A socket is an endpoint of a two-way communication link between two programs running on the network. It’s bound to a port number and TCP or IP protocol. It means every process has only one port and tranport layer protocols .When there are two different computers, it also need to know the IP adress of the other host .the socket is an interface that one program communicate with another program. For upper layer, they don’t need to know how it works ,you don’t need to know how TCP establish connection by three-way handshake and terminate connection by four waves,if they want to send or receive messages ,they only need to import socket
. Python provides an api for developers to use a socket.
1 | import socket |
socket format :socket.socket(family, type[,potocal])
socket type:
socket.AF_UNIX: Is used to communicate between processes on the same machine efficiently
socket.AF_INET: Is used to communicate between processes over a IPV4 network
socket.AF_INET6: Is used to communicate between processes over a IPV6 network
socket.SOCK_STREAM: Connection which is based on the TCP
socket.SOCK_DGRAM: Connection which is based on the UDP
sock.SOCK_RAM: Receive or send the raw datagram not including link level headers
sock.SOCK_SEQPACKET: It will guarantee that message emission would correspond to a single and complete message reception.
After that ,you need to use bind()
to associate the socket with the service address (For TCP ,you need an IP adress and port number)
1 | # bind the socket to your port |
With us build a socket ,we need to use listen(int backlog) method to monitor passive data.
For the parameter in the listen(),it means the max connection for this operating system at the same time.(at least use 1,most use 5)
1 | sock.listen(1) |
Accept() method is used to accept the data after you listen a connection.However ,you need to keep accept state,for the data is sent continuously.Therefore, there is supposed to use while True
to keep accept().
As for why I use two while True
,for the first one ,it’s used to keep TCP connection, after one connection close ,it will keep accept for other TCP connection.For the second one ,it’s used to keep accepting message,after one message received, it will keep receiving other message until no message is sent.
At last , using close() method to close the socket connection.
C/S
Server code:
1 | import socket |
0x01 For Client
Just like the server, the client also needs to use a socket .But it doesn’t have to be so complicated ,you only need to use connect() method to connect to the server.
Client:
1 | import socket |
0x02 Summary
For server:
socket.socket()
–>bind()
–>listen()
–>while True
–>accept()
–>while True
–>recv
–>send()
For client:
socket.socket()
–>connect()
–while True
–>send()
–>recv()