i am creating a private chat server and client with python 3.9, it was working perfectly until i decided to add an admin user with a password and the ability to kick and ban other users.
Now when i start the server and try to login from the client the server crashes and shows me this error: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
I tried to turn off the firewall and any anti-virus softwares but nothing solved my problem, my network configuration has not changed since i created the original program.
here there is the server code:
import socket
import threading
import time
host = '127.0.0.1'
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
msg = message = client.recv(1024)
if msg.decode('ascii').startswith('KICK'):
if nicknames[client.index(client)] == 'admin':
name_to_kick = msg.decode('ascii')[5:]
kick_user(name_to_kick)
else:
client.send('Bel tentativo...'.encode('ascii'))
elif msg.decode('ascii').startswith('BAN'):
if nicknames[client.index(client)] == 'admin':
name_to_ban = msg.decode('ascii')[4:]
kick_user(name_to_ban)
with open('bans.txt', 'a') as f:
f.write(f'{name_to_ban}\n')
print(f'{name_to_ban} bannato!')
else:
client.send('Bel tentativo...'.encode('ascii'))
else:
broadcast(message)
except:
if client in clients:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast('{} uscito dalla chat!'.format(nickname).encode('ascii'))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print("---------------------------------------")
print("Connesso con {}".format(str(address)))
client.send('NICK'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
with open('bans.txt', 'r') as f:
bans = f.readlines()
if nickname+'\n' in bans:
clients.send('BAN'.encode('ascii'))
client.close()
continue
if nickname == 'admin':
client.send('PASS'.encode('ascii'))
password = client.recv(1024).decode('ascii')
if password != 'password':
client.send('REFUSE'.encode('ascii'))
client.close()
continue
nicknames.append(nickname)
clients.append(client)
print("Nickname: {}".format(nickname))
client.send('Connesso al server!'.encode('ascii'))
client.send("-------------------------------------".encode('ascii'))
time.sleep(0.5)
broadcast("{} entrato in chat!".format(nickname).encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
def kick_user(name):
if name in nicknames:
name_index = nicknames.index(name)
client_to_kick = clients[name_index]
clients.remove(client_to_kick)
client_to_kick.send('Sei stato buttato fuori!'.encode('ascii'))
client_to_kick.close()
nicknames.remove(name)
broadcast(f'{name} buttato fuori!'.encode('ascii'))
print("Ascoltando...")
receive()
and here the client:
import socket
import threading
print("-------------------------------------")
nickname = input("Scegli il tuo nickname: ")
if nickname == 'admin':
password = input("Inserisci la password: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))
stop_thread = False
def receive():
while True:
global stop_thread
if stop_thread:
break
try:
message = client.recv(1024).decode('ascii')
if message == 'NICK':
client.send(nickname.encode('ascii'))
next_message = client.serv(1024).decode('ascii')
if next_message == 'PASS':
client.send(password.encode('ascii'))
if client.rect(1024).decode('ascii') == 'REFUSE':
print("Password sbagliata!")
stop_thread = True
elif next_message == 'BAN':
print('Connessione negata, sei bannato!')
client.close()
stop_thread = True
else:
print(message)
except:
print("Errore!")
client.close()
break
def write():
while True:
if stop_thread:
break
message = f'{nickname}: {input("")}'
if message[len(nickname)+2:].startswith('/'):
if nickname == 'admin':
if message[len(nickname)+2:].startswith('/kick'):
client.send(f'KICK {message[len(nickname)+2+6:]}'.encode('ascii'))
elif message[len(nickname)+2:].startswith('/ban'):
client.send(f'BAN {message[len(nickname)+2+5:]}'.encode('ascii'))
else:
print("Comandi accessibili solo a admin!")
else:
client.send(message.encode('ascii'))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
Do somebody know what could be my problem?
Thanks
Related
I have created two chatroom programs. The idea is that the server and client(s) can transfer messages between each other.
The current situation is that the server cannot receive messages whilst entering messages neither can client type messages whilst waiting for server to send.
I have been looking at threading to solve this problem but haven't got a clue to implement it.
Server code:
#Chatroom Server
import socket
import threading
host = socket.gethostname()
ip = socket.gethostbyname(host)
print('Host name:', host)
print('Host IP:' , ip)
port = 8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((ip,port))
name = input('Enter host name:')
s.listen(3)#Allows maximum 3 connections to server
conn,addr = s.accept()
print('Connection established with: ', addr[0])
client = (conn.recv(1024)).decode()
print(client + ' connected')
conn.send(name.encode())
while True:
msg = input('You:')
choice = False
while True:
choice = input('Do you want to enter another line? (Y/N)')
if choice.upper() == 'Y':
add_msg= input("You:")
msg = msg + '\n' +add_msg
else:
break
conn.send(msg.encode())
msg = conn.recv(1024)
msg = msg.decode()
print(client+':'+msg)
Client code:
#Chatroom Client
import socket
hip = 'xxx.xx.xx.xx' #hip = host ip
port = 8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((hip,port))
name = input('Enter username:')
s.send(name.encode())
hname = s.recv(1024)
hname = hname.decode()
while True:
smsg = (s.recv(1024).decode())
print(hname+':'+smsg)
msg = input('You:')
choice = False
while True:
choice = input('Do you want to enter another line? (Y/N)')
if choice.upper() == 'Y':
add_msg= input("You:")
msg = msg + '\n' +add_msg
else:
break
s.send(msg.encode())
I am creating a chat application in which i am using multiprocessing.
The code was too large so i am only sending the main issue of the code, Thanks For your help
Code
import socket,select
from multiprocessing import Process
HEADER_LENGTH = 10
IP = socket.gethostbyname(socket.gethostname())
PORT = 1234
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
sockets_list = [server_socket]
clients = {}
def Run_Server():
def receive_message(client_socket):
try:
message_header = client_socket.recv(HEADER_LENGTH)
if not len(message_header):
return False
message_length = int(message_header.decode('utf-8').strip())
return {'header': message_header,'data':client_socket.recv(message_length)}
except:
return False
while True:
read_sockets, _, exception_sockets = select.select(sockets_list[],sockets_list)
for notified_socket in read_sockets:
if notified_socket == server_socket:
client_socket, client_address = server_socket.accept()
user = receive_message(client_socket)
if user is False:
continue
sockets_list.append(client_socket)
clients[client_socket] = user
print('Accepted new connection')
else:
message = receive_message(notified_socket)
if message is False:
print('Closed connection ')
sockets_list.remove(notified_socket)
del clients[notified_socket]
continue
user = clients[notified_socket]
print(f'Received message')
for client_socket in clients:
if client_socket != notified_socket:
client_socket.send(user['header'] )
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
del clients[notified_socket]
if __name__ =='__main__' :
p1= Process(target=Run_Server)
p1.start()
p1.join()
The output
is blank
but it should be loading server, so i can work with it. I saw many questions like this but couldnt fix the error please tell whats wrong. I event tried without p1.join() but still not working please help me.
I'm a novice when it comes to networking, but for my distributed systems project I'm attempting to create a simple application that allows any computer on the same network with python to send messages to a server. I cannot get my computer and laptop to connect successfully, and I get a timeout error on the client side:
Here is my server code:
import socket
import select
HEADER_LENGTH = 10
IP = "127.0.0.1"
PORT = 1234
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
sockets_list = [server_socket]
clients = {}
def receive_message(client_socket):
try:
message_header = client_socket.recv(HEADER_LENGTH)
if not len(message_header):
return False
message_length = int(message_header.decode("utf-8").strip())
return {"header": message_header, "data" : client_socket.recv(message_length)}
except:
return False
while True:
read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)
for notified_socket in read_sockets:
if notified_socket == server_socket:
client_socket, client_address = server_socket.accept()
user = receive_message(client_socket)
if user is False:
continue
sockets_list.append(client_socket)
clients[client_socket] = user
print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username:{user['data'].decode('utf-8')}")
else:
message = receive_message(notified_socket)
if message is False:
print(f"Closed connection from {clients[notified_socket]['data'].decode('utf-8')}")
sockets_list.remove(notified_socket)
del clients[notified_socket]
continue
user = clients[notified_socket]
print(f"Received message from {user['data'].decode('utf-8')}: {message['data'].decode('utf-8')}")
for client_socket in clients:
if client_socket != notified_socket:
client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
del clients[notified_socket]
Here is my client code
import socket
import select
import errno
import sys
HEADER_LENGTH = 10
IP = "127.0.0.1"
PORT = 1234
my_username = input("Username: ")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
client_socket.setblocking(False)
username = my_username.encode("utf-8")
username_header = f"{len(username):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(username_header + username)
while True:
message = input(f"{my_username} > ")
if message:
message = message.encode("utf-8")
message_header = f"{len(message):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(message_header + message)
try:
while True:
#receive things
username_header = client_socket.recv(HEADER_LENGTH)
if not len(username_header):
print("connection closed by the server")
sys.exit()
username_length = int(username_header.decode("utf-8").strip())
username = client_socket.recv(username_length).decode("utf-8")
message_header = client_socket.recv(HEADER_LENGTH)
message_length = int(message_header.decode("utf-8").strip())
message = client_socket.recv(message_length).decode("utf-8")
print(f"{username} > {message}")
except IOError as e:
if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
print('Reading error', str(e))
sys.exit()
continue
except Exception as e:
print('General error', str(e))
sys.exit()
On the same machine, it works as expected since I'm using the hostname for both the server and client, but obviously, it will not work on separate devices.
How may I change this code so that I can get my laptop to act as a client, and my computer to act as a server? I only need to connect to devices on the same network. Thank you for any answers.
I found the solution myself, I just had to set the 'IP' in client to that of the server local IP, and lastly run both in IDLE so I would get the prompt to bypass the firewall, as I was running cmd previously and was not getting the option to bypass.
I wanted to demonstrate Asynchronous Non-Blocking threads through an EventLoop using a chatroom that I coded out in Python.
The chatroom is working fine when I simulate a server and clients on my desktop, but whenever I want to send packets over the internet to my friends who stay at a geographically distant location, I receive Timeout errors.
Obviously, I change the IP_ADDR accordingly while doing so. In fact, I have tried both IPv4 and IPv6. The firewall is off, and there are no anti-viruses installed.
I tried setting the timeout options as well, but the problem still exists.
Over a small geographical distance, the connection works.
I have also checked whether I am even able to send packets over the Internet at all to the target computer using the tracert command, and it seems like I can.
Server.py
import sys
import select
import msvcrt
import socket
IP_ADDR = socket.gethostbyname(socket.gethostname())
PORT = 5555
HEADER_SIZE = 10
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((IP_ADDR, PORT))
def add_header(username, msg):
username = f'{len(username) :< {HEADER_SIZE}}' + username
msg_len = len(msg)
msg = username + f'{msg_len :< {HEADER_SIZE}}' + msg
return msg.encode("utf-8")
sock_list = [server]
sock_dict = {server : 'Server'}
def broadcast_message(client, broadcast_msg):
try: #EAFP
client.send(broadcast_msg)
except:
username = sock_dict[client]
del sock_dict[client]
sock_list.remove(client)
broadcast_msg = add_header(sock_dict[server], f"{username} has left the group!!")
for clients in sock_list:
if clients is server:
print(f"{username} has left the group!!")
else:
broadcast_message(clients, broadcast_msg)
server.listen()
while True:
readers, _, err_sockets = select.select(sock_list, [], [], 1)
if(msvcrt.kbhit()):
msg = input("[:] >> ")
#msg = sys.stdin.readline()[:-1]
msg = add_header(sock_dict[server], msg)
for client in sock_list:
if client is server:
continue
else:
broadcast_message(client, msg)
for reader in readers:
if reader is server:
client_socc, client_addr = server.accept()
try:
client_username = client_socc.recv(1024).decode("utf-8")
if not len(client_username):
continue
else:
print(f"Connection accepted from {client_username[HEADER_SIZE : ].title()} : {client_addr[0]} : {client_addr[1]}")
sock_dict[client_socc] = client_username[HEADER_SIZE : ].title()
sock_list.append(client_socc)
broadcast_msg = add_header(sock_dict[server], f"{sock_dict[client_socc]} has joined the group!!")
for client in sock_list:
if client is server or client is client_socc:
continue
else:
broadcast_message(client, broadcast_msg)
except:
continue
else:
try:
client_msg = reader.recv(1024).decode("utf-8")
if not len(client_msg):
del sock_dict[reader]
sock_list.remove(reader)
else:
while len(client_msg):
broadcast_msg = add_header(sock_dict[reader], client_msg[HEADER_SIZE : HEADER_SIZE + int(client_msg[:HEADER_SIZE])])
print(f"{sock_dict[reader]} >> {client_msg[HEADER_SIZE : HEADER_SIZE + int(client_msg[:HEADER_SIZE])]}")
client_msg = client_msg[HEADER_SIZE + int(client_msg[:HEADER_SIZE]) : ]
for client in sock_list:
if client is server or client is reader:
continue
else:
broadcast_message(client, broadcast_msg)
except:
continue
Client.py
import sys
import select
import socket
import msvcrt
IP_ADDR = socket.gethostbyname(socket.gethostname())
PORT = 5555
HEADER_SIZE = 10
class Connection():
def __init__(self, default = (IP_ADDR, PORT)):
self.client_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Trying to connect to {default[0]} : {default[1]}")
self.client_conn.connect(default)
print("Connection succesful!")
username = input("Enter your username : ")
username = f'{len(username) :< {HEADER_SIZE}}' + username
self.client_conn.send(username.encode("utf-8"))
def fileno(self):
return self.client_conn.fileno()
def on_read(self):
msg = self.client_conn.recv(1024).decode("utf-8")
self.decode_message(msg)
def decode_message(self, msg):
while len(msg):
username = msg[HEADER_SIZE : HEADER_SIZE + int(msg[: HEADER_SIZE])]
msg = msg[HEADER_SIZE + int(msg[: HEADER_SIZE]) : ]
user_msg = msg[HEADER_SIZE : HEADER_SIZE + int(msg[: HEADER_SIZE])]
msg = msg[HEADER_SIZE + int(msg[: HEADER_SIZE]) : ]
print(f"{username} >> {user_msg}")
class Input():
def __init__(self, client):
self.client = client.client_conn
def fileno(self):
return sys.stdin.fileno()
def on_read(self):
#msg = sys.stdin.readline()[:-1]
msg = input("[:] >> ")
msg_len = len(msg)
msg = f'{msg_len :< {HEADER_SIZE}}' + msg
self.client.send(msg.encode("utf-8"))
connection = Connection()
read_input = Input(connection)
while True:
readers, _, _ = select.select([connection], [], [], 1)
if(msvcrt.kbhit()):
readers.append(read_input)
for reader in readers:
reader.on_read()
I was trying to make a simple chat room using Sockets in python3. When I ran my server on my localhost and set up clients using multiple terminals, everything went fine. When I tried to connect to the server (which was hosted on my system) by another system connected to same LAN network, this error came out.
ConnectionResetError: [Errno 104] Connection reset by peer
When I tried to reconnect from second system again and again it gave me another error
BrokenPipeError: [Errno 32] Broken pipe
This is my server.py
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread
HOST = "192.168.157.206"
PORT = 3000
addresses = {}
clients = {}
def Connections():
while True:
client, addr = server.accept()
print("{} is connected!!".format(addr))
client.send(("Welcome to Chat Room. Type {quit} to exit. Enter your name: ").encode("utf-8"))
addresses[client] = addr
Thread(target = ClientConnection, args=(client, )).start()
def ClientConnection(client):
name = client.recv(BufferSize).decode("utf-8")
client.send(("Hello {}".format(name)).encode("utf-8"))
message = ("{} has joined the chat..").format(name)
Broadcast(message.encode("utf-8"))
clients[client] = name
while True:
msg = client.recv(BufferSize).decode("utf-8")
if msg != "quit":
Broadcast(msg.encode("utf-8"), name + ": ")
else:
message = ("{} has left the chat.").format(clients[client])
Broadcast(message.encode("utf-8"))
client.send(("Will see you soon..").encode("utf-8"))
del clients[client]
break
def Broadcast(msg, name = ""):
for sockets in clients:
sockets.send(name.encode("utf-8") + msg)
server = socket(family=AF_INET, type=SOCK_STREAM)
try:
server.bind((HOST, PORT))
except OSError:
print("Server Busy")
BufferSize = 1024
server.listen(5)
print("Waiting for Connections... ")
AcceptThread = Thread(target=Connections)
AcceptThread.start()
AcceptThread.join()
server.close()
This is my client.py
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread
HOST = input("Enter Host IP: ")
PORT = eval(input("Enter Port No: "))
BufferSize = 1024
def Recieve():
while True:
try:
msg = client.recv(BufferSize).decode("utf-8")
print(msg)
except OSError:
break
def Send():
while True:
msg = input()
if msg == "quit":
client.send(msg.encode("utf-8"))
client.close()
break
else:
client.send(msg.encode("utf-8"))
client = socket(family=AF_INET, type=SOCK_STREAM)
client.connect((HOST, PORT))
RecieveThread = Thread(target=Recieve).start()
SendThread = Thread(target=Send).start()
Please tell me where I went wrong. I went through this answer here. But I cannot figure out where to correct this in my code.
Thanks in advance.