I want to send a list through a TCP socket in python. Then I have to receive the same list on the receiving end. I am currently running into an error regarding the way I send the list. I have also tried to convert the list to str() format and encode it before sending but it also didn't work.
this is my client side:
import socket
import pickle
HEADER = 40
IP = '127.0.0.1'
PORT = 9669
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
package = [1, 5, 0, 0, 0, 'u', 's', 'e', 'r', '1', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
send_package = pickle.dumps(send_package)
client_socket.send(send_package)
this is my server side
import socket
import pickle
HEADER = 40
IP = '127.0.0.1'
PORT = 9669
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((IP,PORT))
server_socket.listen()
client_socket, client_address = server_socket.accept()
receive_message = client_socket.recv(HEADER)
message = pickle.loads(receive_message)
print(type(message))
print(message)
and the terminal on the server side return this:
Traceback (most recent call last):
File "c:/Users/Duong Dang/Desktop/authen/server.py", line 17, in <module>
message = pickle.loads(receive_message)
_pickle.UnpicklingError: pickle data was truncated
There are two problems with your code. The first is a simple typo in your client side. You should change send_package = pickle.dumps(send_package)
to send_package = pickle.dumps(package)
. You do this because you are trying to pickle the package
variable into a new send_package
variable and you can't define a new variable as a function of itself.
The main issue with your code is the header. The HEADER
variable that you have defined refers to the amount of data that you are willing to send. In your case, you chose 40 byes. The issue is that your list is more than the size that you allocated. Thus, you were only able to send a small part of it.
It's a simple fix, just change HEADER
to a bigger number like 4096
and everything will work fine. Here is the description from the documentation: socket.recv