python基于tcp/ip协议的服务端(支持多个客户端同时连接处理)
代码如下:
1 import threading
2 import socket
3
4
5 class Server(object):
6 """服务端"""
7
8 def __init__(self):
9 self.server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
10 self.Address = ("192.168.67.102",7890)
11 self.server_socket.bind(self.Address)
12 self.server_socket.listen(128)
13 self.clientsocket = dict()
14 self.count = 0
15 self.isrunning = dict()
16
17 def WaitClient(self):
18 while True:
19 print("正在等待客户端的连接......")
20 clientsocket,clientAddresss = self.server_socket.accept()
21 print("%s已经连接成功!" % str(clientAddresss))
22 # print(clientsocket,clientAddresss)
23 self.count += 1
24 self.clientsocket[clientAddresss] = clientsocket
25 print("当前客户端连接个数为:%d" % self.clientsocket.__len__())
26 self.isrunning[self.count]=True
27 print("集合中的元素为:%s" % str(self.isrunning.__len__()))
28 t = threading.Thread(target=self.RecvMsg,args = (clientsocket,clientAddresss,self.isrunning,self.count))
29 t1 = threading.Thread(target=self.SendMsg,args=(clientsocket,clientAddresss,self.isrunning,self.count))
30 t.start()
31 t1.start()
32
33 def RecvMsg(self,client,clientaddress,isrun,count):
34 if isrun[count] is True:
35 while True:
36 try:
37 recvmsg = client.recv(1024)
38 print("来自%s的消息为:%s" % (str(clientaddress),recvmsg.decode("utf-8")))
39 except Exception as ret:
40 print("客户端%s已经离去!" % str(clientaddress))
41 client.close()
42 isrun[count] = False
43 self.clientsocket.pop(clientaddress)
44 break
45 else:
46 return
47
48 def SendMsg(self,client,clientAddresss,isrun,count):
49 while True:
50 sendstr = input("请输入你要发送的消息:")
51 if isrun[count] is True: # 先判断该客户端是否还在
52 if client:
53 client.send(sendstr.encode("utf-8"))
54 else:
55 isrun.pop(count)
56 return
57
58
59
60 def main():
61 """测试函数"""
62 S = Server()
63 S.WaitClient()
64
65 if __name__ == '__main__':
66 main()
客户端代码如下:
import socket
import threading
class Client(object):
"""客户端"""
def __init__(self):
self.client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.Address = ("192.168.67.102",9090)
self.client_socket.bind(self.Address)
self.server_Address = ("192.168.67.102",7890)
def ConnectionServer(self):
print(self.client_socket)
self.client_socket.connect(self.server_Address)
print("连接成功!")
t1 = threading.Thread(target=self.SendMsg)
t2 = threading.Thread(target=self.RecvMsg)
t1.start()
t2.start()
def RecvMsg(self):
while True:
recvstr = self.client_socket.recv(1024)
print("接收到来自服务器的消息维为:%s" % recvstr.decode("utf-8"))
def SendMsg(self):
while True:
sendstr = input("请输入你要发送的消息:")
self.client_socket.send(sendstr.encode("utf-8"))
def main():
"""测试函数"""
C = Client()
C.ConnectionServer()
if __name__ == '__main__':
main()