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.
Related
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)
Some util informations:
OS: Windows 10 (with WSL2 installed)
IDE: Emacs
I'm working in a project using the python socket library.
I made a class to organize the server processes, inside that server I have the method "requestConnection", when I call the method it gives me an error "Errno 22 [invalid argument]".
Here's the error:
Traceback (most recent call last):
File "SocketChat.py", line 4, in <module>
servidor.requestConnection()
File "/mnt/c/Users/Mauro/Development/Projects/SocketChat/server.py", line 16, in requestConnection
self.con = self.server_socket.accept()
File "/usr/lib/python3.8/socket.py", line 292, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Here's the main code:
from server import Server, Chat
servidor = Server('127.0.0.1', '5000')
servidor.requestConnection()
chat = Chat(servidor.receiveMsg())
Here's the classes:
import socket
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.addr = (host, port)
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def shutDown(self):
self.server_socket.close()
def requestConnection(self):
self.con = self.server_socket.accept()
def receiveMsg(self):
receive = self.con.recv(1024)
return str(receive)
class Chat:
def __init__(msg):
self.msg = msg
pass
def newMsg(self):
print(f"new message: {self.msg.decode()}")
pass
If you know how to solve this problem, please give-me the answer
Try to pass the port number as integer, not string:
from server import Server, Chat
servidor = Server('127.0.0.1', 5000)
This is my code. Currently it transfers about 75% of the image file (cropped at the bottom). I want it transferred as a whole. This is how I've been working on it:
Create a folder in server pc called "server"
Create a folder in client pc called "client"
Also include the image file you want to transfer in the same "client" folder
Client side ask "name of the file you want to send", I type in the name of the image file in the folder
Aerver side ask me "name of the file you want to receive", I type any random name.
The file transfers and gets saved to "server" folder in the server PC.
client.py
from socket import *
def establish_connection(server_IP, server_port):
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect((server_IP, server_port))
return client_socket
def send_recv_message(client_socket, message, buffer_size):
file = open(filename,'rb')
file_data = file.read(buffer_size)
client_socket.send(file_data)
text=print("File transfered")
return text
server_IP = input("Please, enter server IP address: ")
server_port = input("Please, enter server TCP connection port number: ")
client_socket = establish_connection(server_IP, int(server_port))
print("Connection established\n")
filename= input(str("enter filename"))
received_message = send_recv_message(client_socket,filename,1048576)
server.py
from socket import *
def create_socket(server_port):
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind(('', server_port))
server_socket.listen(1)
return server_socket
def recv_message(server_socket, buffer_size):
file = open(filename, 'wb')
connection_socket, address = server_socket.accept()
file_data= connection_socket.recv(buffer_size)
file.write(file_data)
file.close()
text=("file recieved")
return text
server_port = input("Please, enter TCP connection port number: ")
server_socket = create_socket(int(server_port))
while (True):
filename=input(str("enter filename for the incoming file:"))
incoming_message = recv_message(server_socket, 1048576)
print ("{}" .format(incoming_message))
send may not send the entire buffer. You need to use sendall instead.
recv may not receive all the available data. You need to call recv in a loop until the connection is closed.
this is because the picture is more than the buffer size.
you have to send the size of the pic form client to server..example for text sending this can be used for image to...
eg
send_message = input()
mess = f'{len(send_message)}'.ljust(buffer_size) + send_message
soc.send(mess.encode())
at the server side find the size of picture and while size is not equal to your message recieved keep appending the msg.
message = ''
mes_len = 0
new_msg = True
print('got the connection: {}'.format(self.request))
while True:
data = self.request.recv(buffer_size)
if new_msg:
mes_len = int(data.decode())
new_msg = False
message += data.decode()
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 wrote a client and a server program in which client sends a file to the server and server prints the contents of the file. This is the code snippet:
Server---------------->serverprog.py
import socket
from threading import *
class Server:
gate = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 0
file = ''
def __init__(self, port):
self.port = port
# self.gate.bind((self.host, self.port))
self.gate.bind(("127.0.0.1", self.port))
self.listen()
def listen(self):
self.gate.listen(10)
while True:
conn,address = self.gate.accept()
self.receiveFilename(conn)
def receiveFileName(self, sock):
buf = sock.recv(1024)
print('First bytes I got: ' + buf)
a = Server(8888)
Client ------------------>clientprog.py
import socket
from threading import *
class Client:
gateway = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#host = socket.gethostname()
host = ''
port = 0
file = ''
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()
self.sendFile()
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()
a = Client('127.0.0.1', 8888, 'datasend.txt')
If i compile both client and server simultaneously, it gives me the following error for server program:
Traceback (most recent call last):
File "receivefilepg.py", line 25, in <module>
a = Server(8888)
File "receivefilepg.py", line 15, in __init__
self.listen()
File "receivefilepg.py", line 20, in listen
self.receiveFilename(conn)
AttributeError: Server instance has no attribute 'receiveFilename'
What am i doing wrong here? Any suggestions would be helpful!
The Error tells you all you need to know, you have a typo in the server.listen method, instead of calling self.receiveFileName you called self.receiveFilename.