本文实例为大家分享了python实现聊天小程序的具体代码,供大家参考,具体内容如下
我这里实现的是客户端与服务端进行通信的功能,比较简单,与上一篇文章的群聊不太一样。
服务端server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#-*- 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#-*- 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 )
|
结果展示
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://blog.csdn.net/mtbaby/article/details/79374849