python聊天程序实例代码分享

代码简单,直接看代码吧:

代码如下:

import socketimport threadingimport 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\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\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()

Posted in 未分类

发表评论