Posted in Python onMarch 13, 2018
本文实例为大家分享了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)
结果展示
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
python实现聊天小程序
- Author -
MTbaby声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@