Pickle in Python, incorrect received data - python

I am creating simple server client architecture using pickle. When I receive data and print it, first number disaapear, why? how can I avoid this?
for example: ({2,2,4}, {3,4}) - > ({2,4}, {3,4})
server code:
import pickle
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print ("conn info: ", conn)
objrcv = pickle.loads(conn.recv(10024))
print("conn recv: ", objrcv)
print("conn from: ", addr)
print(objrcv)
client code
import socket
import pickle
name = 'name'
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data = pickle.dumps(name)
s.connect((TCP_IP, TCP_PORT))
# #s.send(data) #powitalne info, dane gracza
def wyslij_dane(my_array): #sending data
data = pickle.dumps(my_array)
if data[0] != 0: # pierwszy argument odpowiedzialny za poddanie sie
print('before send')
s.send(data)
print('after send') #just to control
#data_recv = s.recv(BUFFER_SIZE)
#print("received data:", data_recv)
def rozlacz():#disconnecting
s.close()
wyslij_dane(({2,2,4}, {3,4}))
wyslij_dane({2,2,433})
wyslij_dane(0)
rozlacz()
server output:
conn info: ...
conn recv: ({2, 4}, {3, 4})
conn from: ('127.0.0.1', 51876)
({2, 4}, {3, 4})
And another question is: What can I do to handle all sending data (all call wyslij_dane() funcions)?

"{}" means you are using a set. In a set every item exists only once. Instead you can use a list with these -> "[]" or a tupel -> "()"
So
wyslij_dane(({2,2,4}, {3,4}))
becomes
wyslij_dane(([2,2,4], [3,4]))
and so on.

Related

Sending JSON object to a tcp listener port in use Python

I have a listener on a tcp localhost:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def client_socket():
while 1:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
while 1:
print 'Listening for client...'
conn, addr = s.accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
print "Received all the data"
i=0
for x in param:
print x
#break
elif data:
print "received data: ", data
param.insert(i,data)
i+=1
#print "End of transmission"
s.close()
I am trying to send a JSON object to the same port on the local host:
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender' : local_ip,
'instruction' : direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data)
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data)
data = s.recv(1024)
print('Received', repr(data))
However, I get a socket error:
socket.error: [Errno 98] Address already in use
What am I doing wrong? Will this work or do I need to serialize the JSON object?
There are a few problems with your code, but the one that will likely address your issue is setting the SO_REUSEADDR socket option with:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
after you create the socket (with socket.socket(...) but before you attempt to bind to an address (with s.bind().
In terms of other things, the two "halves" of the code are pretty inconsistent -- like you copied and pasted code from two different places and tried to use them?
(One uses a context manager and Python 3 print syntax while the other uses Python 2 print syntax...)
But I've written enough socket programs that I can decipher pretty much anything, so here's a working version of your code (with some pretty suboptimal parameters e.g. a buffer size of 1, but how else would you expect to catch a single ;?)
Server:
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
BUFFER_SIZE = 1
def server_socket():
data = []
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen()
while 1: # Accept connections from multiple clients
print('Listening for client...')
conn, addr = s.accept()
print('Connection address:', addr)
while 1: # Accept multiple messages from each client
buffer = conn.recv(BUFFER_SIZE)
buffer = buffer.decode()
if buffer == ";":
conn.close()
print("Received all the data")
for x in data:
print(x)
break
elif buffer:
print("received data: ", buffer)
data.append(buffer)
else:
break
server_socket()
Client:
import socket
import json
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8192 # The port used by the server
def json_message(direction):
local_ip = socket.gethostbyname(socket.gethostname())
data = {
'sender': local_ip,
'instruction': direction
}
json_data = json.dumps(data, sort_keys=False, indent=2)
print("data %s" % json_data)
send_message(json_data + ";")
return json_data
def send_message(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(data.encode())
data = s.recv(1024)
print('Received', repr(data))
json_message("SOME_DIRECTION")

Socket Error Python

I had the following code and I cannot observe the behaivour of server and receiver client because client sender pops error continiously. How can I handle this?
Error: An existing connection is forced to shut down by a remote computer
Client Sender
import socket
import sys
serverName = 'localhost'
serverPort = 12000
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((serverName, serverPort))
f = open("sentfile.txt")
l = f.read(2097152)
while(l):
l_bytes = bytes(l, "utf-8")
s.sendall(l_bytes)
Server
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 12000))
s.listen(1)
print ("The server is ready")
conn, addr = s.accept()
with conn:
print('Connected by ', addr)
while True:
data = conn.recv(2097152)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as p:
p.bind(('localhost', 1000))
conn2, addr2 = p.accept()
with conn2:
conn2.sendall(data)
Client Receiver
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('localhost', 1000))
s.listen(1)
conn, addr = s.accept()
with conn:
while True:
f = open('receivedfile.txt', 'ba')
data = connRev(2097152)
f.write(data)
f.close()
first you have to import Socket module. Then use the function getaddrinfo().

how to create a UDP server that will listen on multiple ports in python?

this is my server:
import socket
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
while True:
(client_name, client_adress) = server_socket.recvfrom(1024)
print chr(port)
server_socket.close()
this is my client:
import socket
message = raw_input("Enter a message: ")
for letter in message:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
my_socket.sendto("", ('127.0.0.1', ord(letter)))
(data, remote_adress) = my_socket.recvfrom(1024)
my_socket.close()
print 'The server sent: ' + data
I'm not very good in python, but I think you should save your sockets to list inside for and then use select function in infinite loop outside for
import socket
import select
sockets = []
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
sockets.append(server_socket)
empty = []
while True:
readable, writable, exceptional = select.select(sockets, empty, empty)
for s in readable:
(client_data, client_address) = s.recvfrom(1024)
print client_address, client_data
for s in sockets:
s.close()

Socket programing - constantly send and recive data (python)

I'm programing a very simple screen sharing program.
I have the code for sending and reciving the screen picture. I want the server to be able to recive data at any time, and I want the Client to send the data every 3 seconds. this is the code:
Server:
import socket
import zlib
def conv(code):
with open('Image2.pgm', 'wb') as f:
f.write(code)
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 100000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
str = zlib.decompress(data)
conv(str)
print "All OK"
conn.send(data) # echo
conn.close()
Client:
import socket
import pyscreenshot as ImageGrab
import zlib
def PrtSc():
ImageGrab.grab_to_file("Image.pgm")
f = open("Image.pgm", "rb")
Image = f.read()
Image = zlib.compress(Image)
return Image
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 100000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(PrtSc())
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
Thanks :)

Example for Client socket that try to connect to the server for 2 seconds

Someone can add to my Example under, the code that define the Client socket try to connect to the server for 2 seconds please ?
I read about that and i don't successful to do that, because of that i ask for an example.
Example:
Client:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7777
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
Server:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 7777
BUFFER_SIZE = 20
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data)
conn.close()
Thank you.
Instead of having two separate python files, you can have a single file but put the server and client in separate threads. sys.stdout.write is used instead of print due some concurrency issue with print being buffered (it mixes strings).
import threading
import socket
import sys
class socket_server(threading.Thread):
TCP_IP = "127.0.0.1"
TCP_PORT = 7777
BUFFER_SIZE = 20
daemon = True
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.TCP_IP, self.TCP_PORT))
s.listen(1)
conn, addr = s.accept()
(ip, port) = addr
sys.stdout.write("%s connection address: IP %s on Port %d\n" % (self.__class__.__name__, ip, port))
data = True
while data:
data = conn.recv(self.BUFFER_SIZE)
if data:
sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
send_data = data.upper()
sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, send_data))
conn.send(send_data)
conn.close()
class socket_client(threading.Thread):
TCP_IP = "127.0.0.1"
TCP_PORT = 7777
BUFFER_SIZE = 1024
TIMEOUT = 2.0
MESSAGE = "Hello, World!"
def run(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.TIMEOUT)
s.connect((self.TCP_IP, self.TCP_PORT))
sys.stdout.write("%s sending data: %s\n" % (self.__class__.__name__, self.MESSAGE))
s.send(self.MESSAGE)
data = s.recv(self.BUFFER_SIZE)
s.close()
if data:
sys.stdout.write("%s received data: %s\n" % (self.__class__.__name__, data))
server = socket_server()
client = socket_client()
server.start()
client.start()

Categories