When my server receives the pickle.dumps data and loads it pickle.loads (data) it generates the following error
data_arr = pickle.loads (data)
EOFError: Entry timed out
import socket
import pickle
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
data = conn.recv(4096)
data_arr = pickle.loads(data)
if not data: break
conn.send(data)
conn.close()
Related
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")
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().
I am writing a python program (master.py) to read the data received from 2 separate clients. This is the code example:
master.py:
data_agg = ''
HOST = '172.31.31.207'
PORT = 50008
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(65535)
data_agg += data
if not data: break
data_arr = json.loads(data_agg.decode('utf-8'))
data_arr = sorted(data_arr)
print "Sorted attay: \n"
print data_arr
Two clients have the following code:
HOST = '172.31.31.207'
PORT = 50008
s0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s0.connect((HOST, PORT))
s0.send(sorted_data_string)
s0.close()
However i only receive data from a single client. What would be a proper way to read the data from a socket arriving from multiple receivers?
If you want your server th handle multiple clients, you can put accept() in a loop and add new clients to a list of connected clients. Then you can read - write to each of those clients.
HOST = '172.31.31.207'
PORT = 50008
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2)
clients = []
while True:
conn, addr = s.accept()
clients += [{'conn':conn, 'addr':addr}]
print 'Connected by', addr
data_agg = ''
while True:
data = conn.recv(65535)
if not data:
break
data_agg += data
data_arr = sorted(json.loads(data_agg.decode('utf-8')))
print "Sorted attay: \n"
print data_arr
conn.close()
s.close()
You could improve the above code by using thread, so that you can handle multiple clients at the same time. You can do this by defining a handle_client function, and run it on a new thread.
while True:
conn, addr = s.accept()
print 'Connected by', addr
start_new_thread(handle_client, (conn,))
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 :)
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()