The socket is simple chat python

python based tcp / ip protocol server (support multiple clients simultaneously connecting process)

code show as below:

 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 is          the while True:
 . 19              Print ( " Waiting for client connections ...... " )
 20 is              ClientSocket, clientAddresss = Self. server_socket.accept ()
 21 is              Print ( " % S has been successfully connected! " % STR (clientAddresss))
 22 is              # Print (ClientSocket, clientAddresss) 
23 is              self.count. 1 = +
 24              self.clientsocket [clientAddresss] =ClientSocket
 25              Print ( " the current number of client connections: D% " % self.clientsocket. the __len__ ())
 26 is              self.isrunning [self.count] = True
 27              Print ( " set of elements:% S " % STR (self.isrunning. the __len__ ()))
 28              T of the threading.Thread = (target = self.RecvMsg, args = (ClientSocket, clientAddresss, self.isrunning, self.count))
 29              T1 of the threading.Thread = (target = Self .SendMsg, args = (ClientSocket, clientAddresss, self.isrunning, self.count))
 30              t.start ()
 31 is             t1.start ()
 32  
33 is      DEF recvmsg (Self, Client, clientAddress, isrun, COUNT):
 34 is          IF isrun [COUNT] IS True:
 35              the while True:
 36                  the try :
 37 [                      recvmsg = client.recv (1024 )
 38 is                      Print ( " message is from% s:% s " % (STR (clientAddress), recvmsg.decode ( " UTF-. 8 " )))
 39                  the except Exception aS RET:
 40                      Print ( " !% s client has gone " % STR (clientaddress))
41 is                      client.close ()
 42 is                      isrun [COUNT] = False
 43 is                      self.clientsocket.pop (clientAddress)
 44 is                      BREAK 
45          the else :
 46 is              return 
47  
48      DEF the SendMsg (Self, Client, clientAddresss, isrun, COUNT):
 49              the while True:
 50                  the iNPUT = sendstr ( " Please enter the message you want to send: " )
 51                  iF isrun [COUNT] iS True: # first determine whether the client is still 
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()

Client code as follows:

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 ( " connection success! " ) 
        T1 = of the threading.Thread (target = self.SendMsg) 
        T2 = of the threading.Thread (target = self.RecvMsg) 
        t1.start () 
        t2.start () 


    DEF recvmsg (Self):
         the while True: 
            recvstr = self.client_socket.recv (1024 )
             Print ( " the received message from the server dimension is:% S " % recvstr.decode ( " UTF-. 8 " )) 

    DEF the SendMsg (Self):
         the whileTrue: 
            sendstr  = INPUT (" Please enter the message you want to send: " ) 
            self.client_socket.send (sendstr.encode ( " UTF-8 " )) 

DEF main ():
     "" " test function " "" 
    C = Client () 
    C .ConnectionServer () 
    

IF  the __name__ == ' __main__ ' : 
    main ()

 

Guess you like

Origin www.cnblogs.com/yuanshuang-club/p/11541622.html