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))
Related
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 made the follow class:
class Client(socket.socket):
def __init__(self):
super(Client, self).__init__()
self.settimeout(None)
self.radd = None
self.port = None
self.buffersize = None
def connect_to_server(self):
self.connect((self.radd, self.port))
def configure(self, radd:str, port=49305, buffersize=2048):
# close the socket
self.close()
# assign a new configuration
self.radd = radd
self.port = port
self.buffersize = buffersize
and i used it as follow:
c = Client()
c.configure('192.168.1.1')
c.connect_to_server()
but i get the error: [WinError 10038]
Can anyone tell me why this happens?
Error 10038 is WSAENOTSOCK.
An operation was attempted on something that is not a socket.
It is happening because you are closing the socket before you connect. If you call close(), you have to create a new socket after that.
After some research I found that it is related to the connection. The socket is getting closed before the connection request is coming. But why is it happening, I cant understand
I am getting an error in the server code:
import socket
import threading
import time
data = ''
# This thread manages the client connections
class ClientThread(threading.Thread):
def __init__(self,conn,Address):
threading.Thread.__init__(self)
self.conn = conn
print("New connection added", Address)
def run(self):
print ("Connection from : ", Address)
self.conn.send(bytes("You are connected to IIT H",'utf-8'))
# This thread takes care about recieving the contents of the .txt file
class RecieveThread(threading.Thread):
def __init__(self,conn,Address):
threading.Thread.__init__(self)
self.conn = conn
def run(self):
print("This data is from Housekeeping unit: ",Address)
data = self.conn.recv(1024).decode()
print("The wastebin attributes are: ", data)
host = ''
port = 5000
server_socket = socket.socket()
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((host, port))
print("The IIT-H server is active")
print("Waiting for clients to connect")
server_socket.listen(4)
conn, Address = server_socket.accept()
ClientThread(conn,Address).start()
RecieveThread(conn,Address).start()
conn.close()
Getting the error in the line:
data = self.conn.recv(1024).decode()
Kindly help me
(I have the following code in which I would like to implement a server-side application and to send clients a response:
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
request = ''
while 1:
data = self.sock.recv(1024).decode() # The program hangs here with large message
if not data:
break
request += data
print(request, self.addr[1], self.addr[0]))
message = "test"
self.sock.send(message.encode())
def init_server():
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((host, int(port)))
serversocket.listen(5)
while 1:
clients, address = serversocket.accept()
client(clients, address)
return
Now I write a simple client:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8000))
client_socket.send(message)
request = ''
while 1:
data = client_socket.recv(2048).decode()
if not data:
break
request += data
print(request)
client_socket.close()
The problem now is that the server hangs in recv with a large message. How can I solve it?
Your client socket and server socket are different sockets.
You can get server info using the serversocket object the same way you try self.sock.
I would recommend parsing serversocket as a third argument into your client class, and then using it within the class like so:
class client(Thread):
def __init__(self, socket, address, server):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.server = server
self.start()
def run(self):
request=''
while 1:
data=self.sock.recv(1024).decode()
if not data:
break
request+=data
print(request, self.server.getsockname()[1], self.server.getsockname()[0]))
def init_server():
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((host, int(port)))
serversocket.listen(5)
while 1:
clients, address = serversocket.accept()
client(clients, address, serversocket)
return
That should output the server information.
If you wanted the client information, it's parsed in the 'address' as a tuple, you can see the remote IP address and the socket port used to communicate on (not the open port).
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.