Python套接字-多个客户端 [英] Python Socket - Multiple Clients

查看:231
本文介绍了Python套接字-多个客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先免责声明:我不是Python(或一般编程)方面的专家.

First as a disclaimer: I'm not the greatest at Python(or programming in general).

话虽如此,我在使用Python套接字时遇到了问题.我正在尝试构建一个简单的聊天客户端/服务器程序,但是,我无法让服务器将从一个客户端的套接字接收到的相应消息发送到其余已连接的客户端.

Having said that, I am having issues with Python Sockets. I am trying to build a simple chat client/server program, however, I am unable to have the server send the corresponding message(s) received from one client's socket, to the rest of the connected clients.

这是服务器代码:

#!/usr/bin/python
import socket
import fnmatch
import thread

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Allow socket to be reused by application - doesn't force timeout.
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = socket.gethostname()
port = 9000
serverSocket.bind((host,port))

connectedUsers = []

serverSocket.listen(5)


def threadedClient(clientStream):
        while True:
                clientMessage = clientStream.recv(1024).decode()
                print clientMessage
                if "Username:" in clientMessage:
                        username = clientMessage.replace("Username:","")
                        print str(username) + " has connected!"
                        connectedUsers.append(clientAddress)
                        print str(username) + "" + str(clientAddress) + " has connected to server"
                        for users in connectedUsers:
                                clientStream.sendto(str(username) + " has connected!", users)
                if "Text:" in clientMessage:
                        receievedText = clientMessage.replace("Text:","")
                        for users in connectedUsers:
                                clientStream.sendto(receievedText.encode(), users)
                                print "Sending message " + str(receievedText) +" to:" + str(users)
                if not clientMessage:
                        break



while True:
        clientStream, clientAddress = serverSocket.accept()
        thread.start_new_thread(threadedClient,(clientStream,))

这是客户端代码:

#!/usr/bin/python

import socket

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9000

username = raw_input("Please enter username: ")

clientSocket.connect((host, port))
clientSocket.send("Username:" + username)

def receiveServerMessage():
    serverMessage = clientSocket.recv(1024).decode()
    print serverMessage + '\n'


while True:
    receiveServerMessage()
    command = raw_input(username + " > ")
    if command != None:
        clientSocket.send("Text:" + str.encode(command))
    if command == str("q"):
        exit()
clientSocket.close()

当尝试将消息发送到其他连接的客户端时,迭代似乎很麻烦.我不确定"sendto"是否是处理这种情况的正确方法……尤其是因为我认为它是基于UDP的.关于如何正确处理套接字流的任何建议?

The iteration seems to be awry when attempting to send the message to the other connected clients. I'm not sure if "sendto" is the proper way of handling this situation...especially since I believe it is UDP based. Any suggestions on how to handle socket stream correctly?

推荐答案

问题是客户端在监听服务器套接字之前先监听键盘输入,解决此问题的最佳方法是使用 select( ),类似于c中的 select() 这是一个很好的例子 https://pymotw.com/2/select/

the problem is that the client is listening to the keyboard input before listening to the server socket , the best way to solve this is by using select() which similar to select() in c here is a good example https://pymotw.com/2/select/

这篇关于Python套接字-多个客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆