python socket 简单实现聊天功能

今天看了下python的socket,想实现下两台电脑的聊天功能(觉得这样好像自己写出个简易版QQ没问题了),于是动手开始实现。

首先是服务器端:

from socket import *
from time import ctime

HOST=''
PORT=80   #端口号,服务器与客户端要一致
BUFSIZ=1024    #传送数据的缓冲区大小,随意设置
ADDR=(HOST,PORT)   #链接地址

tcpSS=socket(AF_INET,SOCK_STREAM)
tcpSS.bind(ADDR)
tcpSS.listen(5)
while True:
    print "waiting for connection.."
    tcpCS,addr=tcpSS.accept()
    print "...connected from:",addr
    
    while True:
        data=tcpCS.recv(BUFSIZ)
        if not data:
            exit(0)
        print "[%s] \n%s"%(ctime() ,data)
        data =raw_input('[%s]\n'%ctime())
        tcpCS.send("%s"%data)
    tcpCS.close()
tcpSS.close()
接着是客户端:

from socket import *
from time import ctime
HOST='192.168.1.104'
PORT=80
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpCS=socket(AF_INET,SOCK_STREAM)
tcpCS.connect(ADDR)
while True:   
    data=raw_input('[%s]\n'%ctime())    
    if not data:       
        break    
    tcpCS.send(data)     
    data=tcpCS.recv(BUFSIZ)   
    if not data:        
        break    
    print "[%s]\n%s"%(ctime(),data) 
tcpCS.close()
主要就是数据接收和传送,没什么特别的地方。
简单实现了客户端与服务器的一来一往的对话,并带有时间标签。只是为了玩一下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值