本文实例为大家分享了简单实现python聊天程序的具体代码,供大家参考,具体内容如下
客户端
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
|
#coding:utf-8
import socket, sys
host = 'localhost'
port = 10001
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print 'socket创建成功'
try :
s.connect((host,port))
print '连接成功'
except :
sys.exit( 1 )
while 1 :
try :
date = raw_input ( '客户端:' )
s.send(date)
buf = s.recv( 1024 )
if len (buf):
print '服务端:' + buf
except :
print 'over'
s.close()
sys.exit( 0 )
|
服务端
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
|
# -*- coding: utf-8 -*-
import socket,sys
host = ''
port = 10001
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1 )
s.bind((host,port))
s.listen( 5 )
print '就绪'
clientsock,clientaddr = s.accept()
print '已建立连接'
while 1 :
try :
buf = clientsock.recv( 1024 )
if len (buf):
print '客户端:' + buf
date = raw_input ( '服务端:' )
clientsock.send(date)
except :
print 'over'
clientsock.close()
sys.exit( 0 )
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/wait_nothing_alone/article/details/53284682