Python Thread.start() causes AttributeError - python

While coding a client-server system in python, I came across a weird error in the server stdout, which shouldn't happen:
Traceback (most recent call last):
File "C:\Users\Adam\Drive\DJdaemon\Server\main.py", line 33, in <module>
ClientThread(csock, addr).start()
AttributeError: 'ClientThread' object has no attribute '_initialized'
I split the line up into multiple lines, and it was start() that caused the error.
Any ideas? Here's the server source code- the client just opens and closes the connection:
import socket, threading
class ClientThread(threading.Thread):
def __init__(self, sock, addr):
self.sock = sock
self.addr = addr
def run(self):
sock = self.sock
addr = self.addr
while True:
msg = sock.recv(1024).decode()
if not msg:
print('Disconnect: ' + addr[0] + ':' + str(addr[1]))
sock.close()
return
# Constants
SERVER_ADDRESS = ('', 25566)
MAX_CLIENTS = 10
MCSRV_ADDRESS = ('localhost', 25567)
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(SERVER_ADDRESS)
srv.listen(MAX_CLIENTS)
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
(csock, addr) = srv.accept()
print('Connect: ' + addr[0] + ':' + str(addr[1]))
ClientThread(csock, addr).start()

You forgot to call ClientThread's parent contructor in __init__.
def __init__(self, sock, addr):
super(ClientThread, self).__init__()
self.sock = sock
self.addr = addr

Related

Socket error - return getattr(self._sock,name)(*args)

I have this error when I try to run this on my server can you help me
error:
line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: listen() takes exactly one argument (0 given)
This is my code:
import socket
import threading
HEADER = 64
PORT = 2000
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
conn.send("Msg received".encode(FORMAT))
conn.close()
def start():
server.listen()
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print("[STARTING]")
start()

Server Loop Using Python Sockets and Threading module

I am making server-client communication in python using sockets and threading module. I connect client to server, send some data, receive some data, but the problem is, I can send only two messages. After those, the server is not reciving my packets. Can someone tell me what's wrong? Thanks in advance.
Server.py:
import socket
from threading import Thread
class Server:
def __init__(self):
self.host = '127.0.0.1'
self.port = 9999
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
self.threads = []
self.listen_for_clients()
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print('Accepted Connection from: '+str(addr[0])+':'+str(addr[1]))
self.threads.append(Thread(target=self.handle_client, args=(client, addr)))
for thread in self.threads:
thread.start()
def handle_client(self, client_socket, address):
client_socket.send('Welcome to server'.encode())
size = 1024
while True:
message = client_socket.recv(size)
if message.decode() == 'q^':
print('Received request for exit from: '+str(address[0])+':'+str(address[1]))
break
else:
print('Received: '+message.decode()+' from: '+str(address[0])+':'+str(address[1]))
client_socket.send('Received request for exit. Deleted from server threads'.encode())
client_socket.close()
if __name__=="__main__":
main = Server()
Client.py
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
while True:
data = input()
client.send(data.encode())
message = client.recv(4096)
print('[+] Received: '+ message.decode())
main()
You have to send exit message 'q^' to client too to close client.
Warning:
Using Unicode as encoding for string is not recommended in socket. A partial Unicode character may be received in server/client resulting in UnicodeDecodeError being raised.
Code for server using threads is:
server.py:
import socket
from threading import Thread
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print(
'Accepted Connection from: ' + str(addr[0]) + ':' + str(addr[1])
)
Thread(target=self.handle_client, args=(client, addr)).start()
def handle_client(self, client_socket, address):
size = 1024
while True:
try:
data = client_socket.recv(size)
if 'q^' in data.decode():
print('Received request for exit from: ' + str(
address[0]) + ':' + str(address[1]))
break
else:
# send getting after receiving from client
client_socket.sendall('Welcome to server'.encode())
print('Received: ' + data.decode() + ' from: ' + str(
address[0]) + ':' + str(address[1]))
except socket.error:
client_socket.close()
return False
client_socket.sendall(
'Received request for exit. Deleted from server threads'.encode()
)
# send quit message to client too
client_socket.sendall(
'q^'.encode()
)
client_socket.close()
if __name__ == "__main__":
host = '127.0.0.1'
port = 9999
main = Server(host, port)
# start listening for clients
main.listen_for_clients()
client.py:
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
online = True
while online:
data = input()
client.sendall(data.encode())
while True:
message = client.recv(4096)
if 'q^' in message.decode():
client.close()
online = False
break
print('[+] Received: ' + message.decode())
break # stop receiving
# start client
main()

how to create a UDP server that will listen on multiple ports in python?

this is my server:
import socket
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
while True:
(client_name, client_adress) = server_socket.recvfrom(1024)
print chr(port)
server_socket.close()
this is my client:
import socket
message = raw_input("Enter a message: ")
for letter in message:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
my_socket.sendto("", ('127.0.0.1', ord(letter)))
(data, remote_adress) = my_socket.recvfrom(1024)
my_socket.close()
print 'The server sent: ' + data
I'm not very good in python, but I think you should save your sockets to list inside for and then use select function in infinite loop outside for
import socket
import select
sockets = []
for port in range(33,128):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('0.0.0.0', port))
sockets.append(server_socket)
empty = []
while True:
readable, writable, exceptional = select.select(sockets, empty, empty)
for s in readable:
(client_data, client_address) = s.recvfrom(1024)
print client_address, client_data
for s in sockets:
s.close()

Why this attributeError comes all the time,how i fix this

when i running my chat program,an attribute error is there all the time.
could someone please explain why this error occur in my code and suggest solutions.
the chat program is
import socket
import select
import sys
#list for socket descriptors
socket_list = []
host = socket.gethostname()
port = 5009
def chat_server():
server_socket = socket.socket(socket.AF_INIT, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((host, port))
server_socket.listen(10)
# add server socket to the list
socket_list.append(server_socket)
print "chat server started on port" + str(port)
while 1:
#get the list of sockets to be read through select
read, write, error = select.select(socket_list, [], [])
for sock in read:
if sock == server_socket:
sock_obj, addr = server_socket.accept()
socket_list.append(sock_obj)
print "Client (%s, %s) connected"%addr)
broadcast(srver_socket, sock_obj,
"[%s, %s] entered our chat address" %addr)
else :
#process data recieved from client,
data = sock.recv(4000)
if data :
broadcast(server_socket0, sock,
'Message[' + addr[0] + ':'
+ str(addr[1]) + '] -' + data.strip())
else :
# remove the broken socket
if sock in socket_list :
socket_list.remove(sock)
broadcast(server_socket, sock,
"Client (%s, %s) is offline" %addr)
server_socket.close()
# broadcast the messages to our clients
def broadcast (server_socket, sock, msg):
for sockets in socket_list :
if sockets != server_socket and sockets != sock :
socket.send(msg)
when i run this code the following errors occur,
please give some suggestion to make it correct
Traceback (most recent call last):
File "chat_server.py", line 55, in <module>
chat_server()
File "chat_server.py", line 11, in chat_server
server_socket = socket.socket(socket.AF_INIT, socket.SOCK_DGRAM)
AttributeError: 'module' object has no attribute 'AF_INIT'
Which version you are using, did not find socket.AF_INIT
socket.AF_INET exist in python 2.7 version (https://docs.python.org/2/library/socket.html)

TCP server can only read one message and stops

I am having some trouble in getting this TCP server run properly... When I connect to it with netcat, I can only send one message and then the server does not display the other send messages. When I place client, addr = tcp_socket.accept() out of the while loop I can receive multiple messages but can only connect once...
What is the best way to tackles these problems?
Code
class TCP(threading.Thread):
def __init__(self, host, port):
self.port = port
threading.Thread.__init__(self)
def create_socket(self, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', port))
sock.listen(5)
return sock
def listen(self, tcp_socket):
while True:
client, addr = tcp_socket.accept()
print "Got connection from", addr
data = client.recv(1024)
if data:
print "TCP", data
def run(self):
self.listen(self.create_socket(self.port))
Here's a working example server application which has Socket.accept() outside the loop:
class (threading.Thread):
def listenForClients(self, sock):
while True:
client, address = sock.accept()
client.settimeout(5)
threading.Thread( target = self.listenToClient, args = (client,address) ).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
response = "Got connection"
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
self.listenForClients(sock)
this uses a thread for each client because otherwise Socket.recv() blocks so clients would have to take turns.

Categories