我正在开发一个聊天程序。我有一个服务器和一个客户端,多个用户可以连接到服务器。目前,我只是让服务器发回客户端发送给服务器的任何消息。我想添加身份验证,以便在身份验证失败时接受/拒绝连接。
客户:
class Network:
# initialize the socket
def __init__(self, client, host=host, port=port):
self.client = client;
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
self.port = port;
self.host = host;
self.addr = (host, port);
# conenct to the server
def connect(self):
self.socket.connect(self.addr);
# receive data from server if there is any
def read(self):
while True:
time.sleep(0.1)
try:
data = self.socket.recv(1024);
except:
break;
# instead of breaking, create "connection lost" then open the login form again
print "in client: ", data;
data_split = data.split("\r\n");
for ds in data_split:
self.client.msgbox.addMsg(ds);
# send chat message to the server
def send(self, msg):
self.socket.send(msg);
# authenticate user
# if
def authenticate(self, info):
self.socket.send(info);
服务器:
class Server:
# init the socket
def __init__(self, host=host, port=port):
self.host = host;
self.port = port;
self.addr = (host, port);
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
# send data to client
def send(self, soc, data):
try:
soc.send(data);
except:
return "couldn't send message";
# receive data from client
def receive(self, soc):
while True:
try:
return soc.recv(size);
except:
return disconnect;
# connect client
def connect(self):
self.socket.bind(self.addr);
self.socket.listen(5);
self.socket_s = [self.socket];
self.read_socs = [self.socket];
self.write_socs = [];
self.user_addr = {};
# validate the user
def validate(self, username, password):
if username in users:
sha = s256.new();
sha.update(password);
password = sha.hexdigest();
if password == users[username]:
print "in server: true";
return True;
else:
print "in server: false";
return False;
# server
def serve(self):
while True:
r_socs, w_socs, exceptions = select.select(self.read_socs, [], []);
for s in r_socs:
if s in self.socket_s:
print "accepting socket connect";
soc, address = s.accept();
print "in server: ", soc, address;
self.read_socs.append(soc);
self.write_socs.append(soc);
for ws in self.write_socs:
self.send(ws, "len(users) == " + str(len(self.write_socs)) + "\n");
print connection;
else:
data = self.receive(s);
print "in server: " + data;
if auth in data:
ds = data.split(" ");
res = self.validate(ds[1], ds[2]);
elif data == disconnect:
s.close();
self.read_socs.remove(s);
self.write_socs.remove(s);
for ws in self.write_socs:
print "in server: " + ws
self.send(ws, "len(users) == " + str(len(self.write_socs)) + "\n");
else:
for ws in self.write_socs:
print "in server: " + ws;
self.send(ws, data);