A request to receive data was disallowed, when creating a socket connection - python

I'm making a simple socket connection between server and client, when I want to receive data from the client, and write the data to a text file on the server Destkop, I'm getting an error on line 17 (data = sock.recv(1024)).
Error:
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.
Server:
import socket
import os
import random
randomName = str(random.randint(100, 1001)) + 'data.txt'
FilePath = os.path.join(os.environ['USERPROFILE'], 'Desktop', randomName)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((socket.gethostname(), 9889))
sock.listen(1)
conn, addr = sock.accept()
print(f'{addr} has connected to the server.')
with open(FilePath, 'wb') as f:
if not f.writable():
pass
else:
data = sock.recv(1024)
f.write(data)
exit(0)
Client:
I'm trying to send my computer host name and key ( key is just a string )
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((socket.gethostname(), 9889))
fromServer = sock.recv(1024)
try:
sock.send(socket.gethostname() + key)
except:
print('Cant send hostname and key')

Your code makes a socket object, and binds it to an address at port 9889 as a socket server. When clients connect to this address with a socket connection, the server listens for data, and stores it in the “data” variable.
For receiving data, you should use the connection that was made and not the socket. Therefore:
data = sock.recv(1024)
You should replace sock with conn

Related

Socket programming - Communication between server and client

I'm trying to learn about sockets and how to create a server and a client in python.
While reading this great article from Real Python I had difficulties understanding why the server receives two strings, when I only send one.
server.py
import socket
HOST = "127.0.0.1"
PORT = 65432
server = socket.socket(
family=socket.AF_INET,
type=socket.SOCK_STREAM
)
with server:
server.bind((HOST, PORT))
server.listen()
print("Waiting for connections...")
conn, addr = server.accept()
print("Accepted!")
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
print(f"Message received: {data}")
if not data:
print(f"Breaking while loop and closing connection")
break
conn.sendall(data)
client.py
import socket
HOST = "127.0.0.1"
PORT = 65432
client = socket.socket(
family=socket.AF_INET,
type=socket.SOCK_STREAM
)
with client as c:
c.connect((HOST, PORT))
# Get input from client
message = input("Enter your message: ")
c.sendall(str.encode(message))
data = c.recv(1024)
print(f"Received {data}")
Output from server.py after running the server and client:
Waiting for connections...
Accepted!
Connected by ('127.0.0.1', 64476)
Message received: b'message'
Message received: b''
Breaking while loop and close connection
Why does the server receive two messages (b'message' and b'')
The recv() can only empty string when the other end is gone. You are unable to send zero length data over socket (try it :). So the fact you are seeing this is simply because you are not checking for that.
PS: your client's last print() is not correctly indented.

Client and Server program stuck after creating FTP connection

I have two programs, one for the client and one for the server. I am trying to establish an FTP connection between them to transfer files. The two programs connect okay and I get a confirmation from the server that it has connected to the client's ip, but I get no more output from either program.
Client:
# client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
with open('received_file', 'wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
Server:
# server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print ('Server listening....')
while True:
conn, addr = s.accept() # Establish connection with client.
print ('Got connection from', addr)
data = conn.recv(1024)
print('Server received', repr(data))
filename='text.txt'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
conn.send('Thank you for connecting')
conn.close()
I receive this output from the server:
Server listening....
Got connection from ('192.168.56.1', 51059)
And this from the client:
file opened
receiving data...
But neither program moves past this stage. I'm not sure where in the code that the problem is coming from.

Getting error non-blocking (10035) error when trying to connect to server

I am trying to simply send a list from one computer to another.
I have my server set up on one computer, where the IP address is 192.168.0.101
The code for the server:
import socket
import pickle
import time
import errno
HEADERSIZE = 20
HOST = socket.gethostbyname(socket.gethostname())
PORT = 65432
print(HOST)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, adrs = s.accept()
print(f"Connection with {adrs} has been established")
conn.setblocking(1)
try:
data = conn.recv(HEADERSIZE)
if not data:
print("connection closed")
conn.close()
break
else:
print("Received %d bytes: '%s'" % (len(data), pickle.loads(data)))
except socket.error as e:
if e.args[0] == errno.EWOULDBLOCK:
print('EWOULDBLOCK')
time.sleep(1) # short delay, no tight loops
else:
print(e)
break
The client is on another computer. The code:
import socket
import pickle
HOST = '192.168.0.101'
PORT = 65432
def send_data(list):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
print(".")
print(s.connect_ex((HOST, PORT)))
print(".")
data = pickle.dumps(list)
print(len(data))
s.send(data)
s.close()
send_data([1,1,1])
The outputted error number of connect_ex is 10035. I read a lot about the error, but all I found was about the server side. To me, it looks like the problem is with the client and that it is unable to make a connection to 192.168.0.101. But then, I don't understand why the error I get is about non-blocking.
What is it that I am doing wrong that I am unable to send data?
First of all, how user207421 suggested, change the timeout to a longer duration.
Also, as stated here Socket Programming in Python raising error socket.error:< [Errno 10060] A connection attempt failed I was trying to run my server and connect to a private IP address.
The fix is: on the server side, in the s.bind, to leave the host part empty
HOST = ''
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
And on the client side, use the public IP of the PC where the server is running (I got it from ip4.me)
HOST = 'THE PUBLIC IP' #not going to write it
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, PORT))

'b' is getting passed when sending string from client to server in python while trying FTP implementation

I am trying to implement to implement FTP where I want to send Filename to server from client, I have tried below code, when I give file name as myText.txt but server is receiving as 'b"myText.txt'"
Can you please help me how can I get rid of b ?
This is the output on server:
This is server code:
import socket # Import socket module
port = 60000 # Reserve a port for your service.
socketObj = socket.socket() #Create a socket object
host = socket.gethostname() # Get local machine name
socketObj.bind((host, port)) # Bind to the port
socketObj.listen(5) # Now wait for client connectionection.
print ('Server listening....')
while True:
connection, addr = socketObj.accept() # Establish connectionection with client.
print ('Got connectionection from', addr)
data = connection.recv(1024)
print('Server received request for FTS of',(data))
filename=(repr(data))
f = open(filename,'rb')
l = f.read(1024)
while (l):
connection.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
connection.send(('Thank you for connectionecting').encode())
connection.close()
This is the client code
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
fileNeeded = input("What File do you need, please enter the name:")
s.send(fileNeeded.encode())
fileToBeSaved = input("Enter file name to save requested file")
with open(fileToBeSaved, 'wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = s.recv(1024)
print((data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully got the file')
s.close()
print('connection closed')
The following is received in server:
Server received request for FTS of b'mytext.txt'
You can use the bytes.decode() method to convert bytes into a string:
Change:
filename=(repr(data))
to:
filename=repr(data).decode()

Socket.error: [Errno 10022] An invalid argument was supplied

#!/usr/bin/env python
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('192.168.1.123', 5162))
clientsocket.send('getval.1')
clientsocket.close
clientsocket.bind(('192.168.1.124', 5163))
clientsocket.listen(1)
while True:
connection, address=clientsocket.accept()
value=connection.recv(1024)
print value
I'm trying to get python to send a message to the server, and in return the server responds. Yet when I execute this code it gives me
Socket.error: [Errno 10022] An invalid argument was supplied
It seems you wrote a mixed code of server and client
Here a simple sample of codes for socket programming the first on server side and the second on client
Server side code:
# server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
and now the client
# client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))
The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection

Categories