SOLVED using the following:
Python Socket Receive Large Amount of Data
I have server and client. I try to send bytes over sockets from client to server. However, when it actually tries to send the bytes, it failed with error: socket.error errno 90 message too long. Is there any way to get over this error?
Client:
from socket import socket, AF_INET, SOCK_DGRAM
import pyscreenshot as ImageGrab
SERVER = 'xxxx.xxxx.xxxx.xxxx'
PORT = 5000
mySocket = socket(AF_INET, SOCK_DGRAM)
while True:
im = ImageGrab.grab(bbox=(0,27,320,266))
im.save('test.png')
myfile = open('test.png')
bytes = myfile.read()
mySocket.sendto(bytes, (SERVER, PORT))
myfile.close()
Server:
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import cv2
from PIL import Image
import io
PORT_NUMBER = 5000
SIZE = 150000
hostName = gethostbyname( '0.0.0.0' )
mySocket = socket(AF_INET, SOCK_DGRAM)
mySocket.bind((hostName, PORT_NUMBER))
while True:
(data, addr) = mySocket.recvfrom(SIZE)
image = Image.open(io.BytesIO(data))
image.save('test.png')
imga = cv2.imread('test.png', 0)
sys.exit()
So now I use TCP connection.
New client:
from socket import socket, AF_INET, SOCK_STREAM
import pyscreenshot as ImageGrab
SERVER = 'xxxx.xxxx.xxxx.xxxx'
PORT = 5000
mySocket = socket(AF_INET, SOCK_STREAM)
mySocket.connect((SERVER, PORT))
while True:
im = ImageGrab.grab(bbox=(0,27,320,266))
im.save('test.png')
myfile = open('test.png')
bytes = myfile.read()
mySocket.sendall(bytes)
myfile.close()
New Server:
from socket import socket, gethostbyname, AF_INET, SOCK_STREAM
import cv2
from PIL import Image
import io
import time
PORT_NUMBER = 5000
SIZE = 150000
hostName = gethostbyname( '0.0.0.0' )
mySocket = socket(AF_INET, SOCK_STREAM)
mySocket.bind((hostName, PORT_NUMBER))
mySocket.listen(1)
conn, addr = mySocket.accept()
print("Test server listening on port {0}\n".format(PORT_NUMBER))
while True:
data = conn.recv(SIZE)
last_time = time.time()
image = Image.open(io.BytesIO(data))
image.save('test.png')
imga = cv2.imread('test.png', 0)
print('loop took {} seconds'.format(time.time() - last_time))
sys.exit()
So when I try to run both, I get the following error:
(important: when i send over the sockets small amount of bytes it is successfuly sent, but when it's quite big amount of bytes the following error occurs)
C:\Users\Tal\test\Scripts\python.exe
C:/Users/Tal/PycharmProjects/test/tester.py
Test server listening on port 5000
Traceback (most recent call last):
File "C:\Users\Tal\test\lib\site-packages\PIL\ImageFile.py", line 221, in load
s = read(self.decodermaxblock)
File "C:\Users\Tal\test\lib\site-packages\PIL\PngImagePlugin.py", line 621, in load_read
cid, pos, length = self.png.read()
File "C:\Users\Tal\test\lib\site-packages\PIL\PngImagePlugin.py", line 115, in read
length = i32(s)
File "C:\Users\Tal\test\lib\site-packages\PIL\_binary.py", line 77, in i32be
return unpack_from(">I", c, o)[0]
struct.error: unpack_from requires a buffer of at least 4 bytes
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Tal/PycharmProjects/test/tester.py", line 23, in <module>
image.save('test.png')
File "C:\Users\Tal\test\lib\site-packages\PIL\Image.py", line 1935, in save
self.load()
File "C:\Users\Tal\test\lib\site-packages\PIL\ImageFile.py", line 227, in load
raise IOError("image file is truncated")
OSError: image file is truncated
Process finished with exit code 1
Related
i can recv info from client but i dont know how to recv it from server.
"i think in line 15 i need to change "socket" to somethong"
it must be that type: 'socket.socket'
client:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
client.connect(('127.0.0.1', 1002)) # 127.0.0.1
while True:
command = input('>>>')
if command == 'stop':
exit()
command = command.encode('utf-8')
client.send(command)
get = socket.recv(2048)
get = get.decode('utf-8')
print('recieve',get)
server:
import socket
import subprocess
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # AF_INET = IP, SOCK_STREAM = TCP
server.bind(('127.0.0.1', 1002)) # 127.0.0.1
server.listen()
client_socket, client_address = server.accept()
print(type(client_socket))
while True:
get = client_socket.recv(2048)
get = get.decode('utf-8')
print('recieve',get)
output = subprocess.check_output(get, shell=True)
client_socket.send(output)
output from client:
File "C:\Users\rusla\Desktop\client.py", line 15, in <module>
get = socket.recv(1024)
AttributeError: module 'socket' has no attribute 'recv'
Im trying to send a file over TCP connection and im spected to receive an accio command but, im having trobule doing that, im getting this error:PS C:\Users\mpgm1\PycharmProjects\pythonProject1> py client.py 131.94.128.43 54634 file.txt
4 131.94.128.43 54634 file.txt
confirm-accio
confirm-accio-again
Sending...
Done Sending
b'ERROR: No data expected until the accio command is issued!'
Here is the code:
import selectors
from socket import *
import sock
import sys
print(len(sys.argv), sys.argv[1], sys.argv[2], sys.argv[3])
host = sys.argv[1]
port = int(sys.argv[2])
file = sys.argv[3]
# Instaniating socket object
s = socket(AF_INET, SOCK_STREAM)
# Getting ip_address through host name
host_address = gethostbyname(host)
# Connecting through host's ip address and port number using socket object
s.connect((host_address, port))
print("confirm-accio\r\n")
print("confirm-accio-again\r\n")
fileToSend = open("file.txt", "rb")
print("Sending...")
while True:
data = fileToSend.read()
if not data:
break
s.send(data)
fileToSend.close()
s.send(b"Done")
print("Done Sending")
print(s.recv(1024))
s.close()
I have a simple client server program and the server side works but for some reason I can't get the the client to interact to the server. I am able to launch the server and use nc -6 fe80::cbdd:d3da:5194:99be%eth1 2020 and connect to it.
Server code:
#!/usr/bin/env python3
from socket import *
from time import ctime
HOST='::'
PORT = 2020
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET6, SOCK_STREAM)
##tcpSerSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('Waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connected from:', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send(('[%s] %s'%(bytes(ctime(), 'utf-8'), data)).encode('utf-8'))
tcpCliSock.close()
tcpSerSock.close()
client code:
#!/usr/bin/python3
from socket import *
def tcp_ipv6():
HOST = 'fe80::cbdd:d3da:5194:99be%eth1'
PORT = 2020
ADDR = (HOST, PORT)
BUFSIZ = 1024
sock = socket(AF_INET6, SOCK_STREAM)
sock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
sock.send(data)
response = sock.recv(BUFSIZ)
if not response:
break
print(response.decode('utf-8'))
sock.close()
tcp_ipv6()
When I run the client code I get:
Traceback (most recent call last):
File "client.py", line 44, in <module>
tcp_ipv6()
File "client.py", line 31, in tcp_ipv6
sock.connect(ADDR)
OSError: [Errno 22] Invalid argument
Edit1:
Thanks to Establishing an IPv6 connection using sockets in python
4-tuple for AF_INET6
ADDR = (HOST, PORT, 0, 0)
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
sock.connect(ADDR)
Still having the same error
Any idea?
Thanks in advance
Some parts of your question have been asked before.
Establishing an IPv6 connection using sockets in python
However, it is not the entire reason why it is not working correctly. If you look at your IPv6 address. fe80::cbdd:d3da:5194:99be%eth1 You can see the %eth1 at the end. That is not part of the internet address. Change HOST to HOST = 'fe80::cbdd:d3da:5194:99be'. And it should work.
I would also like to point out another error in your code. You are attempting to send a string (received from input) over the socket. However, this method only accepts byte like objects. You can add data = data.encode('utf-8') to fix this.
The higher level function - create_connection , to connect to port works in such case. Sample scriptlet is given as follows. Though why sock.connect fails needs to be identified.
HOST = "xxxx::xxx:xxxx:xxxx:xxxx%en0"
PORT = 2020
ADDR = (HOST, PORT)
BUFSIZ = 1024
sock=create_connection(ADDR)
I'm new to socket programming in python. Here is an example of opening a TCP socket in a Mininet host and sending a photo from one host to another. In fact I have changed the code which I used to send a simple message to another host (writing the received data to a text file) in order to meet my requirements.
But when I run this code, I encounter this error at sender side:
144
Traceback (most recent call last):
File mmyClient2,pym, line 13, in <module>
if(s.sendall(data)):
File m/usr/lib/python2.7/socket.pym, line 228, in meth
return yetattr[self,_sockename](*args)
File m/usr/lib/python2.7/socket.pym, line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket,error: [Errno 9] Bad file descriptor
So what's wrong?
Receiver.py
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('10.0.0.1', 12345))
buf = 1024
f = open("2.jpg",'wb')
s.listen(1)
conn , addr = s.accept()
while 1:
data = conn.recv(buf)
print(data[:10])
#print "PACKAGE RECEIVED..."
f.write(data)
if not data: break
#conn.send(data)
conn.close()
s.close()
Sender.py:
import socket
import sys
f=open ("1.jpg", "rb")
print sys.getsizeof(f)
buf = 1024
data = f.read(buf)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))
while (data):
if(s.sendall(data)):
#print "sending ..."
data = f.read(buf)
#print(f.tell(), data[:10])
s.close()
There seems to be a problem with s.sendall(), because when I change it to s.send(), there is no error and photo transfer is successful. So my question is: Although I was suggested to use s.sendall() instead of s.send() in my previous question on this site, Is it wrong not to do this?
After send all data, you closed socket.And use closed socket again, that cause error.You can write sender like this.
import socket
import sys
f=open ("1.jpg", "rb")
print sys.getsizeof(f)
buf = 1024
data = f.read(buf)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))
while 1:
if not data:
break
s.sendall(data)
data = f.read(buf)
s.close()
i am trying to create a server/client in python using sockets for sending text and other media files.
Scenario:- Client takes host, port and file name as parameters and send the file to server.
Error Description:- while trying to execute the below client code, having text file "tos" in same directory as client.Getting below error.
**$ python Cli.py 127.0.0.1 5007 tos**
Traceback (most recent call last):
File "Cli.py", line 32, in <module>
client= Client(host,port,file)
File "Cli.py", line 15, in __init__
self.connect(file)
File "Cli.py", line 20, in connect
self.sendFile(file)
File "Cli.py", line 26, in sendFile
readByte = open(file, "rb")
**IOError: [Errno 2] No such file or directory: ''**
Note:- Also please describe if there is anyway to send file to server, searching the hard drive.
Server:-
from socket import *
port = 5007
file = ''
class Server:
gate = socket(AF_INET, SOCK_STREAM)
host = '127.0.0.1'
def __init__(self, port):
self.port = port
self.gate.bind((self.host, self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
print("Listening for connections, on PORT: ", self.port)
add = self.gate.accept()
self.reciveFileName()
self.reciveFile()
def reciveFileName(self):
while True:
data = self.gate.recv(1024)
self.file = data
def reciveFile(self):
createFile = open("new_"+self.file, "wb")
while True:
data = self.gate.recv(1024)
createFile.write(data)
createFile.close()
server= Server(port)
listen()
Client:-
#!/usr/bin/env python
from socket import *
host = ''
port = 5007
file = ''
class Client:
gateway = socket(AF_INET, SOCK_STREAM)
def __init__(self, host,port, file):
self.port = port
self.host = host
self.file = file
self.connect()
def connect(self):
self.gateway.connect((self.host, self.port))
self.sendFileName(file)
self.sendFile(file)
def sendFileName(self):
self.gateway.send("name:" +self.file)
def sendFile(self):
readByte = open(self.file, "rb")
data = readByte.read()
readByte.close()
self.gateway.send(data)
self.gateway.close()
client= Client(host,port,file)
connect()
At the moment file = '' which in not a valid filename. I would also suggest renaming file to filename for clarity.
Had this task as Homework 3 months ago.
The solution for this is pretty simple - You simply need to read the file, put the readed text in a string variable and send it. Look at this server code:
HOST = '192.168.1.100'
PORT = 8012
BUFSIZE = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(SOMAXCONN)
fileOpen = open("D:/fileLocation.txt")
g = f.read()
print 'Waiting For Connection..'
clientsock, addr = serversock.accept()
print 'Connection Established From: ', addr`
clientsock.sendall(g)
This is a very simple way to do so.
The client simply receives the data (as text) and save it in the wanted location.
Worked for me with BMP,PNG and JPG images also.