This article mainly introduces the chat program written in python, which has two threads, namely the client and server. you can refer to the simple code to directly read the code:
The code is as follows:
Import socket
Import threading
Import re
# Import Tkinter
Def ser ():
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
S. bind ('', 33333 ))
S. listen (1)
Conn, addr = s. accept ()
While True:
Print '[% s: % d] send a message to me: % s' % (addr [0], addr [1], conn. recv (1024 ))
S. close ()
Def clt ():
C = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
Ip_pattern = re. compile (r' ^ (\ d {1, 2} | 1 \ d | 2 [0-4] \ d | 25 [0-5]) \. (\ d {1, 2} | 1 \ d | 2 [0-4] \ d | 25 [0-5]) \. (\ d {1, 2} | 1 \ d | 2 [0-4] \ d | 25 [0-5]) \. (\ d {1, 2} | 1 \ d | 2 [0-4] \ d | 25 [0-5]) $ ')
While True:
Ip = raw_input ('input the Server \'s IPv4 address :')
Ip_match = ip_pattern.match (ip)
If ip_match:
Break
C. connect (ip, 33333 ))
While True:
Sms = raw_input ('input the message you want to send :')
C. sendall (sms)
C. close ()
If _ name __= = "_ main __":
Ser = threading. Thread (target = ser)
Clt = threading. Thread (target = clt)
Ser. start ()
Clt. start ()
Ser. join ()
Clt. join ()