python3 如何实现实时聊天功能

cyx441984694 2018-03-25 08:35:48
小白请教python3聊天室功能实现

代码来源:http://blog.csdn.net/calling_wisdom/article/details/42524745

用pycharm测试时候发现,Client那边,A输入一行字,B不能马上收到。需要B先打东西,然后才能收到A的信息。与此同时,A才能收到。
跪求大神解答。好像是threading的问题,还是说pycharm的问题?

Server:

#!/usr/bin/python3
#coding=utf-8

from socket import *
from threading import Thread

HOST='localhost'
PORT=5550
BUFSIZE=1024
ADDR=(HOST,PORT)

Sock = socket(AF_INET,SOCK_STREAM)
Sock.bind(ADDR)
Sock.listen(5)
print("Server 127.0.0.1 listening...")

mydict=dict()
mylist=list()

##whatToSay send to all exceptNum
def tellOthers(mynum,whatToSay):
for c in mylist:
if c.fileno() != mynum:
try:
c.send(whatToSay.encode())
except:
pass

def subThreadIn(myconnection,connNumber):
nickname = myconnection.recv(BUFSIZE).decode()
mydict[myconnection.fileno()]=nickname
mylist.append(myconnection)
print('Connection',connNumber,'has nickname:',nickname)
while True:
try:
recveMsg=myconnection.recv(BUFSIZE).decode()
if not recveMsg:
pass
else:
print(mydict[connNumber],':',recveMsg)
tellOthers(connNumber,mydict[connNumber]+':'+recveMsg)
except(OSError,ConnectionResetError):
try:
mylist.remove(myconnection)
except:
pass
print(mydict[connNumber],'exit,',len(mylist),'person left')
tellOthers(connNumber,'[Remind:'+mydict[connNumber]+' has left the chatting room]')
myconnection.close()
return

while True:
connection,addr=Sock.accept()
print('Accept a new connection',ADDR,connection.fileno())
try:
buf = connection.recv(BUFSIZE).decode()
if buf == '1':
connection.send(b'Welcome to server!') ##Client端显示

mythread = Thread(target=subThreadIn,args=(connection,connection.fileno()))
mythread.setDaemon(True)
mythread.start()
else:
connection.send(b'please go out!')
connection.close()
except:
pass


##Client

from socket import *
from threading import Thread

HOST='localhost'
PORT=5550
BUFSIZE=1024
ADDR=(HOST,PORT)

Sock=socket(AF_INET,SOCK_STREAM)

Sock.connect(ADDR)

Sock.send(b'1')
print(Sock.recv(BUFSIZE).decode())
nickname=input("input your nickname:")
Sock.send(nickname.encode())

def sendThreadFunc():
while True:
try:
myword=input(">>>")
myword=myword.encode('utf-8')
print(Sock.recv(BUFSIZE).decode()) ##这里先后顺序并没有差别的。
Sock.send(myword)
except ConnectionAbortedError:
print('Warning! The connection is aborted!')
except ConnectionResetError:
print("Warning! The connection is reset!")

def recvThreadFunc():
while True:
try:
otherword=Sock.recv(BUFSIZE)
if otherword:
print(otherword.decode())
else:
pass
except ConnectionResetError:
print("Warning! The connection is reset!")
except ConnectionAbortedError:
print("Warning! The connection is aborted!")

send1=Thread(target=sendThreadFunc)
recv1=Thread(target=recvThreadFunc)
threads=[send1,recv1]

for t in threads:
t.setDaemon(True)
t.start()
t.join()
...全文
785 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
DarkChampion 2018-03-30
  • 打赏
  • 举报
回复
print(Sock.recv(BUFSIZE).decode())   ##这里先后顺序并没有差别的。
            Sock.send(myword)
谁告诉你顺序没有差别的?
cyx441984694 2018-03-29
  • 打赏
  • 举报
回复
引用 1 楼 weixin_41004677 的回复:
然而我测试,客户端发送,服务器端会收到
你好,我测试过的是客户端那边不能实时同步。A,B都是客户端,需要等对方按了回车键才可以。是哪里有问题吗?
weixin_41004677 2018-03-26
  • 打赏
  • 举报
回复
然而我测试,客户端发送,服务器端会收到

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧