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.
Related
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)
I have made a multithreaded Python socket server.
It supports multiple socket client connections.
My code is:
import socket
from _thread import *
def multi_threaded_client(connection):
response = ''
while True:
data = connection.recv(10000000)
response += data.decode('utf-8')
if not data:
print(response)
break
connection.send(bytes(some_function_name(response), "utf-8"))
connection.close()
class socketserver:
def __init__(self, address='', port=9090):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.address = address
self.port = port
self.sock.bind((self.address, self.port))
self.cummdata = ''
def recvmsg(self):
self.sock.listen(65535)
self.conn, self.addr = self.sock.accept()
print('connected to', self.addr)
self.cummdata = ''
start_new_thread(multi_threaded_client, (self.conn, ))
return self.cummdata
def __del__(self):
self.sock.close()
serv = socketserver('127.0.0.1', 9090)
print('Socket Created at {}. Waiting for client..'.format(serv.sock.getsockname()))
while True:
msg = serv.recvmsg()
I also want the server to detect if any new client is connected to /disconnected from it.
Once all the clients are disconnected from it, I want the server to be closed on its own.
I could not figure this out
I am trying to listen and send data to several sockets at the same time. When I run the program I get en error saying:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/ssl.py", line 704, in __init__
if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
OSError: [Errno 9] Bad file descriptor
The first socket starts up correctly, but once I try to start a new one I get the error.
class bot:
def __init__(self, host, port):
self.host = host
self.port = port
sock = socket.socket()
s = None
def connect_to_server(self):
self.s = ssl.wrap_socket(self.sock)
self.s.connect((self.host, self.port))
Above is the class and then I'm running several instances.
def run_bots(bots):
for bot in bots:
try:
threading.Thread(target=bot.connect_to_server()).start()
except:
print(bot.host)
print("Error: unable to start thread")
bots = []
b = bot('hostname.com', 1234)
b1 = bot('hostname1.com', 1234)
bots.append(b)
bots.append(b1)
run_bots(bots)
I don't know what to do. Anyone have an idea of what could be the problem?
You are using the same socket. Create one for each bot:
class bot:
def __init__(self, host, port):
self.host = host
self.port = port
self.s = None
def connect_to_server(self):
sock = socket.socket()
self.s = ssl.wrap_socket(sock)
self.s.connect((self.host, self.port))
I get the following error when I want to run this code. I made a mistake I do not understand where all the normal
Where do you think the error
import socket,time
import thread
class http():
def __init__(self):
self.socket = socket
self.port = 5000
self.buffsize = 1024
self.listen = 5
self._header = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n")
def _worker(self,socket,sleep):
# Client connect for thread worker
while True:
time.sleep(sleep)
client,address = socket.accept()
data = client.recv(1024)
if data:
client.send(self._header)
client.send(data)
client.close()
def httpHandler(self):
# Create Socket For Connection
try:
self.socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.socket.bind(('127.0.0.1',self.port))
self.socket.listen(self.listen)
self.socket.setblocking(False)
except socket.error as error:
print error
finally:
print "HTTP Server Running - 127.0.0.1:5000"
self._worker(self.socket,1)
if __name__ == "__main__":
application = http()
application.httpHandler()
When I want to run on the terminal, the error
but how can it be said there is the problem of self-
HTTP Server Running - 127.0.0.1:5000
Traceback (most recent call last):
File "/Users/batuhangoksu/http.py", line 44, in <module>
application.httpHandler()
File "/Users/batuhangoksu/http.py", line 40, in httpHandler
self._worker(self.socket,1)
File "/Users/batuhangoksu/http.py", line 22, in _worker
client,address = socket.accept()
AttributeError: 'module' object has no attribute 'accept'
Use self.socket, not socket:
client,address = self.socket.accept()
socket is the name of the module. self.socket is a socket._socketobject, the value returned by a call to socket.socket. Verily, there are too many things named "socket" :).
I suggest changing self.socket to something else to help separate the ideas.
You also need to save the return value when you call socket.socket. Currently, you have
self.socket = socket
which sets the instance attribute self.socket to the module socket. That's not useful, since you can already access the module with plain old socket. Instead, use something like
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
import multiprocessing as mp
import socket
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
def server():
header = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=utf-8\r\n\r\n")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
while True:
conn, addr = s.accept()
data = conn.recv(1024)
if not data: break
conn.send(header)
conn.send(data)
conn.close()
def client():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
sproc = mp.Process(target = server)
sproc.daemon = True
sproc.start()
while True:
time.sleep(.5)
client()
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.