python实现聊天小程序 python实现聊天小程序
MTbaby 人气:1想了解python实现聊天小程序的相关内容吗,MTbaby在本文为您仔细讲解python实现聊天小程序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python聊天小程序,python聊天室,python聊天,python小程序,下面大家一起来学习吧。
我这里实现的是客户端与服务端进行通信的功能,比较简单,与上一篇文章的群聊不太一样。
服务端server.py
#-*- coding:utf-8 -*- import socket, traceback, sys host = '' port = 51423 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) ClientSock, ClientAddr = s.accept() while 1: try: buf = ClientSock.recv(1024) if len(buf): print "客户端说: " + buf data = raw_input("服务端说: ") ClientSock.sendall(data) except: print "Dialogue Over" ClientSock.close() sys.exit(0)
客户端client.py
#-*- coding:utf-8 -*- import socket, sys host = '192.168.80.21' # host = raw_input("Plz imput destination IP:") # data = raw_input("Plz imput what you want to submit:") port = 51423 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) except socket.gaierror, e: print "Address-related error connecting to server: %s" % e sys.exit(1) except socket.error, e: print "Connection error: %s" % e sys.exit(1) while 1: try: data = raw_input("客户端说: ") s.send(data) buf = s.recv(1024) if len(buf): print "服务端说: " + buf except: print "Dialogue Over" s.close() sys.exit(0)
结果展示
加载全部内容