我正在尝试向特定客户发送消息。我已经制作了一个向所有客户端发送消息的服务器,但我不知道如何向特定客户端发送消息。 ,这是我的服务器代码:
server.py
from socket import *
from codecs import decode
#from chatrecord import ChatRecord
from threading import Thread
from time import ctime
class ClientHandler(Thread):
def __init__(self,client,address):
global sockets
global addresses
Thread.__init__(self)
self._client = client
self._address = address
sockets.append(self._client)
addresses.append(self._address)
def run(self):
self._client.send('Welcome to the chatroom!\n')
while 1:
message =self._client.recv(BUFSIZE)
print '\n\n',sockets
if not message:
print "Client disconnected."
addIndex=sockets.index(self._client)
del sockets[addIndex]
del addresses[addIndex]
self._client.close()
break
else:
if 'ONLINE#' in message:
for x in sockets:
if (x!=self._client):
try:
x.send(message[7:])
except:
print 'disconnected'
continue
print message[7:]
else:
for x in sockets:
try:
x.send(message)
/*sockets is the list of all client*/
except:
print ' '
continue
print message
HOST = 'localhost'
PORT = 1235
ADDRESS = (HOST,PORT)
BUFSIZE = 1024
server = socket(AF_INET,SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)
sockets=[]
addresses=[]
while True:
print "Waiting for connection..."
client, address = server.accept()
print('...client connected from: ',address)
handler = ClientHandler(client,address)
handler.start()
答案 0 :(得分:0)
由于这是一个聊天室,我会在连接时为客户创建一个带有昵称的字典。
客户端会收到提示 - >选一个名字!
客户选择:clientname = jimbob
mydict = {}
mydict[clientname] = self._address
然后,您只需通过昵称
获取用户for client,addr in mydict.iteritems():
if client == "jimbob":
destinationaddr = addr
break
自从我完成python以来已经有一段时间了,所以你可能想把它当作更多的伪代码。
您可能还想查找SocketServer
的文档编辑:您还需要查看客户端连接时是否采用该昵称。它将与上面的for循环非常相似,除非用户存在,否则可以设置一个布尔值。