Python socket (Socket Error Bad File Descriptor) - python

The following receiveFile() function reads a filename and file data from the socket and splits it using the delimiter $.
But I am unable to close the socket and a Bad file descriptor error is raised. If I comment out the self.server_socket.close() statement then there is no error but the socket is listening forever.
Code:-
def listen(self):
self.server_socket.listen(10)
while True:
client_socket, address = self.server_socket.accept()
print 'connected to', address
self.receiveFile(client_socket)
def receiveFile(self,sock):
data = sock.recv(1024)
data = data.split("$");
print 'filename', data[0]
f = open(data[0], "wb")
#data = sock.recv(1024)
print 'the data is', data[1]
f.write(data[1])
data = sock.recv(1024)
while (data):
f.write(data)
data=sock.recv(1024)
f.close()
self.server_socket.close()
print 'the data is', data
print "File Downloaded"
Traceback:-
Traceback (most recent call last):
File "server.py", line 45, in <module>
a = Server(1111)
File "server.py", line 15, in __init__
self.listen()
File "server.py", line 20, in listen
client_socket, address = self.server_socket.accept()
File "c:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "c:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

You are closing the server's listening socket, and after that calling again accept() on it.
To finish receiving one file you should close client connection's socket (sock in function receiveFile).

in this code i am trying to shut down the server once file is received
What you'll need is something to break out of the while True loop when you want to shut down the server. A simple solution would be to exploit the exception generated when you close the server socket...
def listen(self):
self.server_socket.listen(10)
while True:
try:
client_socket, address = self.server_socket.accept()
except socket.error:
break
print 'connected to', address
self.receiveFile(client_socket)
print 'shutting down'

Related

Python sockets - WinError 10054

I'm trying to make a client and server where the client sends a string to the server and the server sends a response back.
This is the method on my client
def send(self):
s = socket.socket()
s.connect(("127.0.0.1", 5012))
message = bytes("Send!", "utf-8")
s.send(message)
data = s.recv(1024)
data = str(data, "utf-8")
print(data)
s.close()
this is a method in the server which waits for client messages.
def listener(self):
print("Startet")
s = socket.socket()
s.bind(("127.0.0.1", 5012))
s.listen(1)
while True:
c, addr = s.accept()
while True:
data = c.recv(1024)
data = str(data, "utf-8")
print(data)
c.send(bytes("OK", "utf-8"))
c.close()
Running this I get:
Startet
Send!
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Anaconda3\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "C:\workspace\Server.py", line 41, in listener
data = c.recv(1024)
ConnectionAbortedError: [WinError 10053]
An established connection was disconnected by the software on the hostcomputer
It prints out the Send!, so at least it recieves the messages, but then abruptly stops. The server should be able to run at all times, and take an
arbitrary amount of messages from the clients send function.
The client does a send() and then immediately a recv() without checking if data is available (e.g. using accept()). If the socket is non-blocking the recv() immediately returns (or it excepts for some other reason). An empty string is printed and the socket is closed. That's why the server gives an ConnectionAbortedError, the client has already closed the connection. Check this by adding a try/except around the client recv().

Traceback Error in Python Code when runs of Ubuntu

I wrote this code that functions properly on Windows but gives a few errors on my Ubuntu 12.04. Although the code performs well its intended function but its given some errors which I don't want.. Kindly help me in this regard..
from socket import *
from threading import Thread
from Crypto.Cipher import AES
import os
import base64
import timeit
# Receiveing + Decoding the Information, symmetrical key isi
def clientHandler():
conn, addr = s.accept()
print addr, "is connected"
while 1:
data = conn.recv(1024)
if not data:
break
print "Metering Data Received: Processing..."
#creating decoding unpadding
PADDING ="{"
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
#creating a default key
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
decrypted_data = DecodeAES(obj2,data)
print decrypted_data
HOST = "" #localhost
PORT = 12000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
print "Server is runnig"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(4):
Thread(target=clientHandler).start()
s.close()
And this is what appears on the terminal of Ubuntu but not on Windows based...
Server is runnig
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "chat_encrypt.py", line 10, in clientHandler
conn, addr = s.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "/usr/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
for i in range(4):
Thread(target=clientHandler).start()
s.close()
The last line closes the socket ... which each thread then tries to 'accept'.

Python client server to send a file Beginner Error

I am trying to do simple code to send file from the client to the server after saving in t some data.
I am a beginner so I can't figure where the problem is or what is the missing function or line in my code
The Server :
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 1024
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:
break
fileREC=open (data , 'rb')
The Client
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
TextFile= open ("TextFile","w")
TextFile.write("Here is the file")
TextFile.write("Writing data")
TextFile.close()
f=open (TextFile , 'wb')
print ("Writing the file to binart ")
client_socket .send(f)
print ("Data Sent")
The Error
ERROR:Traceback (most recent call last):
File "tenmay.py", line 5, in <module>
client_socket.connect(("192.168.1.4", 8000))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Send the contents of the file not the filehandle:
f=open ("TextFile", 'rb')
client_socket.send(f.read())
The second time the client runs the server is waiting to recv data because the accept() command is outside of the loop.
The client could repeatedly send data from a loop, but not if the program ends and has to be restarted.

Socket connection won't close?

I'm trying to write a simple server program that prints the data sent to it, or quits if the data is "quit", "exit", or "stop":
HOST = ""
PORT = 37720
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(1)
while(1):
conn, addr = server.accept()
data = conn.recv(1024)
if not data: break
inData, inUrl = json.loads(data)
if inData == "quit" or inData == "exit" or inData == "stop":
print("Quitting")
conn.close()
break
else:
conn.send("Received")
print(inData)
It does what I expect, except that when I try to run the server again once it's quit, I get:
Traceback (most recent call last):
File "./s", line 14, in <module>
server.bind((HOST, PORT))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
I assume this means the connection wasn't closed. How can I close it to prevent this? I tried the conn.close(), but it didn't fix anything.
You need to set SO_REUSEADDR flag.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Python : file transfer giving errors

I am trying to send a file from a server to client but get errors. Please let me know where I am doing wrong.
This is my server code:
if msg in data.keys():
print("Requested file exists", msg)
f=open(msg,"rb")
datam= f.read(1024)
while (datam):
if(s.send(datam)):
print "sending data"
datam = f.read(1024)
s.close()
f.close
else:
print("File Not found",msg)
print("File Not found",data.keys())
c.close() # Close the connection
where msg contains the path address where file exists
c=client socket s=server socket
I want to read that file and send it to client but I get this error
Got connection from ('127.0.0.1', 42330)
('Requested file exists', '/home/beenish/Pictures/pew.txt')
Traceback (most recent call last):
File "server.py", line 41, in <module>
if(s.send(datam)):
socket.error: [Errno 32] Broken pipe
On client side, I have written this code to recieve that file
s.listen(15)
f = open('\home\beenish\pictures\lol.txt', 'wb')
data = s.recv(1024)
while(data):
f.write(data)
data=s.recv(1024)
f.close()
s.close # Close the socket when done
where s is the client socket
Here I get this error
Traceback (most recent call last):
File "client.py", line 26, in <module>
s.listen(15)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
On the client side you have an error on this line:
s.listen(15)
And the Python docs say that the argument has a system dependant maximum, usually 5. So try finding out the maximum for your system of just use a lower value and see what happen.
The server side error could be a side effect of the client side failure.
That is the kind of error you get when you call socket.listen before calling socket.bind. Keep in mind that a server always has to follow the sequence socket(), bind(), listen() and accept() in that specific order.

Categories