字符串变量无法正确打印

时间:2016-08-14 02:28:15

标签: python python-2.7 sockets chat

所以我正在编写一个多客户端聊天,我想在消息前面显示每个客户端的名称。当我打印变量" client_name"在main函数中(行" clients_dictionary [current_socket.getpeername()]"返回它应该的值,不返回None)它本身显示正常但是当我尝试将它连接到消息正文时(" data = client_name +":" + data")它打印为":变量数据"。我做错了什么?

import socket
import select
HOST = ""
PORT = ""
open_client_sockets = []
messages_to_send = []
clients_dictionary = {}


def handle(server_socket):
    client_socket, client_address = server_socket.accept()
    open_client_sockets.append(client_socket)
    client_name = client_socket.recv(1024)
    clients_dictionary[client_address] = client_name


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)
    while True:
        r, w, x = select.select([server_socket] + open_client_sockets, open_client_sockets, [])
        for current_socket in r:
            if current_socket == server_socket:
                handle(server_socket)
            else:
                try:
                    data = current_socket.recv(1024)
                except socket.error:
                    data = ""
                if data == "":
                    open_client_sockets.remove(current_socket)
                else:
                    client_name = clients_dictionary[current_socket.getpeername()]
                    data = ": " + data
                    data = client_name + data
                    print data
                    messages_to_send.append((current_socket, data))
                    w.remove(current_socket)
                    for client_socket in w:
                        if client_socket != current_socket:
                            client_socket.send(data)

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

无论如何你最好使用python字符串格式化:

chat_msg = '{}: {}'.format(client_name, data)