Socket programming based on the TCP protocol
Realization of telephone communication, for example, here to pass the characters, you can try to send a file yourself.
# server-side import socket # 1. TCP-compliant cell phones server = (socket.AF_INET,socket.SOCK_STREAM) # TCP # 2. Bind a cell phone number to a server. If we use our own computer as a server, we use our own IP address. (('127.0.0.1',8000)) # 127.0.0.1 for local # (('192.168.11.251',8000)) (5) # Semi-connection pools can receive five clients at once. # 3. waiting for client connection print('start...') # Link loops while True: # Communication loop conn,client_addr = () while True: try: # 4. receive data = (1024) # How many bytes received each time, if changed to 10, the client input dir, (you can enter dir in cmd, see what will get), what will happen it, the next blog will talk about sticky packets, and how to deal with sticky packets problem print(data) # 5. (()) except ConnectionAbortedError: continue except ConnectionResetError: break
# Client 1 import socket # 1. Create TCP-compliant cell phones client = (socket.AF_INET,socket.SOCK_STREAM) # 2. dialing (('127.0.0.1',8000)) while True: msg = input('please enter your msg') # dir # 3. Send a message (('utf8')) # 4. Receive messages data = (1024) print(data)
# Client 2 import socket # 1. Create TCP-compliant cell phones client = (socket.AF_INET,socket.SOCK_STREAM) # 2. dialing (('127.0.0.1',8000)) # msg = input('please enter your msg>>>') # 3. Send a message ('hello'.encode('utf8')) ('world'.encode('utf8')) # 4. Receiving information data = (1024) print(data)
Emulate ssh remote execution commands (linux system)
# ssh server import socket import subprocess server = (socket.AF_INET,socket.SOCK_STREAM) (('192.168.11.251',8000)) # This is my machine, the client can be anyone else's machine # (5) print('start...') while True: conn,cient_addr = () print(client_addr) # It prints out the IP of someone else's machine # while True: try: cmd = (1024) # dir print(cmd) # Execute cmd commands for you and then save the results to a pipeline pipeline = (('utf8'), shell = True, stderr = , # std standard stdout = ) stderr = () stdout = () (stderr) (stdout) except ConnectionResetError: break
# ssh client import socket # 1. Create a TCP-compliant cell phone client = (socket.AF_INET,socket.SOCK_STREAM) # 2. dialing (('192.168.11.210',8000)) while True: msg = input('please enter your msg') # dir # 3. Send a message (('utf8')) # 4. Receive messages data = (10) print(('gbk')) # existmacOn the computer it could be'utf8'
The most effective way to learn is to have input and output, so that what you learn can really be useful.
This is the whole content of this article.