Socket is a programming language's encapsulation of the TCP/IP protocol. It can be used to transfer files between two hosts. The following will directly enter the topic. The following example is the simplest example of TCP transmission code. Start the server and then the client. It should be noted that python3socket can only transmit byte type. For specific conversion, please review the relevant knowledge of character encoding chapter
sever code
# - *- coding:utf-8-*-import socket
server = socket.socket()
server.bind(("0.0.0.0",8888))
server.listen(10)while True: #Loop monitoring of connected clients
conn,addr = server.accept()while True: #Each client continues to interact after connecting, and interacts with the next client when the client is disconnected
try:
rec_data = conn.recv(4096) #4096 receive buffer size
iflen(rec_data)==0:breakprint("rec_data:", rec_data.decode(encoding="utf-8"))
conn.send(rec_data.upper())
except ConnectionResetError as e:print("A client closed the connection")break
server.close()
client code
import socket
client = socket.socket()
client.connect(("127.0.0.1",8888))while True:
msg =input()iflen(msg)==0:continue
client.send(msg.encode(encoding="utf-8")) #If you want to send Chinese, you need to encode it, and you also need to receive it. You also need to decode; add b directly before English to specify the type
client_rec = client.recv(4096)print("client_rec:", client_rec)
client.close()
Sticky package solution: For two send statements that are next to each other, there will be a situation where the content of the previous send and the content of the next send are mixed. This is because send only sends data to os, and how the os sends data cannot be controlled. , Use the following method to solve the problem of message sticking between two send statements
server code
import socket, os
server = socket.socket()
server.bind(("0.0.0.0",8888))
server.listen(10)while True: #Loop monitoring of connected clients
conn,addr = server.accept()while True: #Receive the get filename sent by the client, send the file if filename exists, otherwise return the file does not exist
try:
rec_data = conn.recv(1024) #4096 receive buffer size
iflen(rec_data)==0:break
rec_str_list = rec_data.decode(encoding="utf-8").split(" ")
filename = rec_str_list[-1]if os.path.isfile(filename):#Judge that the file exists in the current path and send the file to the client
file_data =open(filename,encoding="utf-8").read()
conn.send(str(len(file_data)).encode(encoding="utf-8")) #Pass the file length to the client
print(conn.recv(1024).decode(encoding="utf-8")) #The client receives the file length and returns a confirmation message, and the server starts to transmit data after receiving the confirmation message
conn.sendall(file_data.encode(encoding="utf-8"))#Send all the data to the client, and the client will send the received message after judging that the data has been received
print(conn.recv(1024).decode(encoding="utf-8")) #Receive the confirmation command received by the client to avoid two send directly connected together to produce sticky packets
else:#If the file name does not exist, return the file does not exist
conn.send(b"file is not exit")
except ConnectionResetError as e:print("A client closed the connection")break
server.close()
client code
import socket, os
# Enter the get file name, when the file exists in the server home directory, the file will be returned, and the client will receive the file content and print it.
client = socket.socket()
client.connect(("127.0.0.1",8888))while True:
msg =input()iflen(msg)==0:continue
client.send(msg.encode(encoding="utf-8")) #If you want to send Chinese, you need to encode it, and you also need to receive it. You also need to decode; add b directly before English to specify the type
client_rec = client.recv(1024).decode(encoding="utf-8")print("client_rec", client_rec)if client_rec =="file is not exit": #If the file does not exist, the user prints the file does not exist, and the user continues to input
print(client_rec)continue
client.send(client_rec.encode(encoding="utf-8"))#Send back the file size if the file exists
rec_len =int(client_rec)print("rec_len", rec_len)
file_len =0
new_file =open("new_file","a",encoding="utf-8")while file_len < rec_len:#Start receiving files in a loop until the received file size is the same as the size sent from the server,Write the received data to a new file
rec_data_tmp = client.recv(1024)
file_len +=len(rec_data_tmp)print("receive date len", file_len)
new_file.write(rec_data_tmp.decode(encoding="utf-8"))
client.send("receive all".encode(encoding="utf-8"))
client.close()
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts