-
Scoket concept:
Essentially between the socket 2 interworking network computers, set up a channel, the two computers to transfer data to each other is achieved through this channel. We know that network communications are based on ip + port before being positioned to target specific services on specific machines, operating systems have 0-65535 ports, each port can independently provide services if a company likened to a computer, and that the company's main number is equivalent to ip addresses, each employee is equivalent to the extension port, you are looking for a personal company, you must first call the switchboard, and then transfer extension. After establishing a socket must have at least 2 terminal, a server, a client, the server passively waits for and receives a request, the client initiates the request, the connection is established, the two sides can send each other data. (IP and port communicate using two devices). -
Socket core methods:
Receiving end: Import Socket socket.TCP/IP listen(ip,port) Waiting () # waiting for data the recv () # reception data Send () # resending data
Sending end: Import Socket socket.TCP/IP Connect (a.ip, a.port) # receiving end host IP, port (port: the port number) socket.send (Hello) # data transmission SendAll () is disposable nominally transmit all the data, but since the system the reason there are limits socket.recv () # receive data socket.close () # close
-
Examples cited:
Server-side: Import socket Server = socket.socket () # Set the connection server.bind (( "localhost", 8888)) # bound connections (a parameter tuple) server.listen (. 5) # monitor conn, addr = server.accept () # wait data = conn.recv (1024) # receiving (a type byte needs to be converted (typically compiled for. 8-UTF)) conn.sendall (data) # -time transmission of all data (due to system reasons, it is not transmitted all data) server.close ()
Client: Import socket client=socket.socket() Client = Connect (( "localhost", 8888)) # to establish a connection, the parameter is a tuple Data = INPUT (). Strip () # manually input is unicode type, but when retransmission is to be coded client.send (data.encode ( "utf-8")) # transmit data data = client.recv (1024) # of data is received utf-8 encoded, so the direct output distortion client.close ()
-
Stick package:
When you continuously call send (), due upon receipt of recv () is limited in size, the amount of data transmitted will happen to the amount of data received, resulting in received data not what you expected data, this time occurred stick package ( data is sent twice with a reception) to avoid this error, we usually design feedback that you send data once, we will send the right data feedback to be sent to you. Such a two received transmission mingled, leading to avoid the sticking of data packets in a buffer. -
Some caveats:
- Type of transmission and reception:
We Python3, the default is Unicode, while transmission data (Send), function send () parameter types are: Byte, so we have to convert the data:
str==>bytes | bytes==>str |
a = "qweqwe" => a of type str str==>bytes b=a.encode(“utf-8”) |
b = b "hello word" => b bytes of type bytes==>str s=b.decode(“utf-8”) |
- Data validation:
String type, we can use the md5 algorithm hashlib package to test
File type, we can compare the difference between two files:
diff file1 file2 |
Observe whether two files are consistent (file detection) |
SocketServer:
This is convenient, it integrates a number of things, very convenient, just about writing server-side changes the way the client without changing
code show as below:
# The this IS Server Import SocketServer class MyTCPHandler (of SocketServer.BaseRequestHandler): # class name at random, but can not change the inherited DEF handle (Self): # The system will automatically call this function, we only need to write in this function we want to achieve method on it the while True: the try : self.data=self.request.recv(1024).strip() print("{} wrote".format(self.client_address)) print(self.data) self.request.send(self.data.upper()) except ConnectionResetError as e: print("error: ",e) break if __name__ =="__main__": HOST, PORT = " localhost " , 9999 # statement IP and port Server = socketserver.ThreadingTCPServer ((HOST, PORT), MyTCPHandler) # Set the connection server.serve_forever () # establish a connection, then the system will automatically call the function after the connection is successful handle ()
#this is client import socket client=socket.socket() client.connect(("localhost",9999)) while True: cmd=input(">>").strip() if cmd =="": continue client.send(cmd.encode()) data=client.recv(1024) print(data)
Attachment:
One of the most simple socket communication:
# Server: Import socket server=socket.socket() server.bind(("localhost",8888)) server.listen() conn,addr=server.accept() count=10 while count: data=conn.recv(1024) print(data.decode("utf-8")) conn.send(data) count-=1 server.close()
# Client Import socket client=socket.socket() client.connect(("localhost",8888)) while True: chioce=input(">>").strip() client.sendall(chioce.encode("utf-8")) data=client.recv(1024) if not data: break print(data.decode("utf-8")) client.close()