简单实现python聊天程序

本文实例为大家分享了简单实现python聊天程序的具体代码,供大家参考,具体内容如下

客户端

#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)

服务端

# -*- 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)

以上是 简单实现python聊天程序 的全部内容, 来源链接: utcz.com/z/324395.html

回到顶部