Python client server to send a file Beginner Error - python

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.

Related

Python Socket SSL OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (wh

Full error code:
Traceback (most recent call last):
File "C:\path\to\my\python\code\server_ssl_testing.py", line 15, in <module>
response = ssock.recv(1024).decode("utf-8")
File "C:\Program Files\Python39\lib\ssl.py", line 1228, in recv
return super().recv(buflen, flags)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
I created SSL Socket server and client, but then server try to receive info from client it falied and print error that is above this text.
Server:
import socket
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('certs/server-cert.pem', 'certs/server.key')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind(('localhost', 2642))
sock.listen(5)
with context.wrap_socket(sock, server_side=True) as ssock:
conn, addr = ssock.accept()
response = ssock.recv(1024).decode("utf-8")
print(response)
Client:
import socket
import ssl
hostname = 'localhost'
context = ssl.create_default_context()
sock = socket.create_connection((hostname, 2642))
ssock = context.wrap_socket(sock, server_hostname=hostname)
msg = "Hello World!"
ssock.send(msg.encode("utf-8"))
In server.py I should write conn.recv instead of ssock.recv.
Should help if anyone will want do it in future =)

Handle ConnectionResetError: [Errno 104] in python

I got this error with python's tcp socket
Traceback (most recent call last): File "servidor_tcp_python.py",
line 205, in
ejecucion_servidor() File "servidor_tcp_python.py", line 27, in ejecucion_servidor
data = connection.recv(10000) ConnectionResetError: [Errno 104] Connection reset by peer
#Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('x.x.x.x', 10000)
print('starting up on %s port %s' % server_address)
sock.bind(server_address)
sock.listen(25)
while True:
# Wait for a connection
print ('waiting for a connection')
try:
connection, client_address = sock.accept()
print('connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
#with decode we convert byte to string, default decode is utf-8
data = connection.recv(10000)
print("Datos recibidos sin decodificar: "+str(data))
try:
data=data.decode("utf-8")
print("Datos recibidos decodificados: "+data)
#
#...... #
except UnicodeDecodeError:
break
except ConnectionResetError:
break
As you can see, I handle and catch the exception with the line
except ConnectionResetError:
break
But it is not working. Why? Should I close the connection after the except?

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().

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 socket (Socket Error Bad File Descriptor)

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'

Categories