Hello, as I am learning python and I entered this network area and exchange information, I would like to get some questions about the code I created trying to make a console interact with a server.
Server Code:
import socket
import sqlite3
from threading import Thread, get_ident
def aceitar_conexoes():
while True:
# print(get_ident(),' accept')
client,address = SERVER.accept()
print('%s:%s se conectou.'%(address[0],address[1]))
addresses[client] = address
Thread(target=conexao_cliente, args=(client,)).start()
def conexao_cliente(client):
try:
welcome = 'Seja bem-vindo!'
client.send(bytes(welcome,'utf8'))
clients.append(client)
while True:
# print(get_ident(),' handle')
msg = client.recv(BUFF)
msg = msg.decode()
if msg == 'database':
c.execute("SELECT * FROM users")
result = str(c.fetchall())
msg = 'Server: %s' % result
client.send(msg.encode())
elif msg == 'clients':
msg = 'Server: %s' % str(clients)
client.send(msg.encode())
elif msg == 'broadcast':
msg = 'exemplo de broadcast'
broadcast(msg)
else:
print(msg)
except ConnectionResetError:
client.close()
clients.remove(client)
def broadcast(msg, prefix="Server: "):
for sock in clients:
sock.send(bytes(prefix, "utf8") + msg.encode())
addresses = {}
clients = []
if __name__ == '__main__':
conn = sqlite3.connect('serverdb.db',check_same_thread=False)
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY,name TEXT, password TEXT)")
c.execute("INSERT INTO users(name,password) VALUES('usuario1','senha1')")
HOST = ''
PORT = 9090
BUFF = 1024
ADDR = (HOST, PORT)
SERVER = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
SERVER.bind(ADDR)
SERVER.listen(5)
print('Aguardando conexões...')
ACCEPT = Thread(target=aceitar_conexoes)
ACCEPT.start()
ACCEPT.join()
SERVER.close()
Customer Code:
from threading import Thread
import socket
def receive():
while True:
msg = client_socket.recv(BUFF).decode()
print(msg)
def send():
while True:
msg = input('Console: ')
if msg == 'clear':
clear()
else:
client_socket.send(bytes(msg, 'utf8'))
def clear():
return print('\n'*50)
if __name__ == '__main__':
clear()
HOST = '127.0.0.1'
PORT = 9090
BUFF = 1024
ADDR = (HOST, PORT)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(ADDR)
print('conectado com %s:%s' % ADDR)
Thread(target=receive).start()
Thread(target=send).start()
The program is working perfectly on the connections part, the problem is when sending the messages to the client. Sometimes when the server sends a message to the client, it appears in the input area.
ex. I write in the console some of the test commands, it gives some bugs
conectado com 127.0.0.1:9090
Seja bem-vindo!
Console: broadcast
Console: Server: exemplo de broadcast
(o input está aqui)
Console: database
Console: Server: [(1, 'usuario1', 'senha1')]
(input aqui de novo)
Console:
The commands look like this when you run the client in pycharm, python console and windows console (different PC). When I open the windows console (on the same server PC) it does not look like this for all messages, just broadcast.
I wonder if anyone has any indication for this kind of thing I'm trying to do, or else indicate some python library. Thanks!