python - 同时发送/接收消息套接字python

标签 python sockets send recv

我一直在开发一个简单的 python 套接字聊天室,客户端和服务器可以在其中相互发送消息。我遇到的问题是服务器和客户端一次只能发送一条消息。我希望它像任何其他聊天室一样工作,我可以在发送消息时收到消息,任何帮助都会有很大帮助

服务器.py

import socket
import sys

s = socket.socket()
host = socket.gethostname()
print(" server will start on host : ", host)
port = 8080
s.bind((host,port))
name = input(str("Please enter your username: "))
print("")
print("Server is waiting for incoming connections")
print("")
s.listen(1)
conn, addr = s.accept()
print("Recieved connection")
print("")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")
conn.send(name.encode())

while 1:
    message = input(str("Please enter your message: "))
    conn.send(message.encode())
    print("Sent")
    print("")
    message = conn.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")

客户端.py

import socket
import sys

s = socket.socket()
host = input(str("Please enter the hostname of the server : "))
port = 8080
s.connect((host,port))
name = input(str("Please enter your username : "))
print(" Connected to chat server")

s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print("")
print(s_name, "has joined the chat room ")

while 1:
    message = s.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")
    message = input(str("Please enter your message: "))
    message = message.encode()
    s.send(message)
    print("Sent")
    print("")

最佳答案

CaSper has given me the server code where multiple clients can connect to the server but the problem now is that the clients can not talk to each other …

这主要是因为您的客户端需要 s_name = s.recv(1024),而 CaSper 的服务器不发送其名称。这是您的客户端的一个变体(期望 hostport 作为命令参数),它与 CaSper 的服务器一起工作并且还解决了您的原始问题(客户端只能发送一条消息一次)通过使用单独的线程:

import socket
import sys

s = socket.socket()
s.connect((sys.argv[1], int(sys.argv[2])))
name = input(str("Please enter your username : "))
print(" Connected to chat server")
s.send(name.encode())

def receive_and_print():
    for message in iter(lambda: s.recv(1024).decode(), ''):
        print(":", message)
        print("")
import threading
background_thread = threading.Thread(target=receive_and_print)
background_thread.daemon = True
background_thread.start()

while 1:
    s.send(input("Please enter your message: ").encode())
    print("Sent")
    print("")

注意 CaSper 的服务器有一系列的不足:

  1. 即使现在您的客户可以随时发送消息,服务器仍会等待来自一个接一个客户的消息,即。 e.当它等待客户端 A 时,客户端 B 可以发送消息,但服务器只有在客户端 A 发送了一些内容后才会接收并广播它。
  2. 它不处理客户端断开连接。
  3. 当所有客户端断开连接时,它进入忙循环。

有关更好的服务器示例,请参阅问题 Handle multiple requests with select .

… could you possibly change my server so that it works …

这是与此客户端一起使用的服务器的变体,也使用单独的线程进行输入和接收:

import socket
import sys

s = socket.socket()
host = socket.gethostname()
print(" server will start on host : ", host)
port = 8080
s.bind((host,port))
name = input(str("Please enter your username: "))
print("")
print("Server is waiting for incoming connections")
print("")
s.listen(1)
conn, addr = s.accept()
print("Recieved connection")
print("")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")

def input_and_send():
    while 1:
        message = name+" : "+input(str("Please enter your message: "))
        conn.send(message.encode())
        print("Sent")
        print("")
import threading
background_thread = threading.Thread(target=input_and_send)
background_thread.daemon = True
background_thread.start()

for message in iter(lambda: conn.recv(1024).decode(), ''):
    print(s_name, ":", message)
    print("")

关于python - 同时发送/接收消息套接字python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621028/

相关文章:

python - 创建 csv 文件中特定行的字典

python - 如何将文件夹中的所有 JPG 文件转换为 PDF 并将它们合并?

windows - closesocket() 偶尔卡住一次

tcp - 如何使用 TCP 或 UDP 将数据从 Windows Phone 8.1 发送到 PC?

python - 将 matplotlib 绘图轴设置为数据框列名称

python - 模块未找到错误: No module named 'wtforms'

c - 如何干净地中断 recv 调用中阻塞的线程?

node.js - Socket.IO和Electron无法发射或接收

c++ - 在 C++ 中通过 winsock 发送 Unicode 字符串

python + django+ EmailMultiAlternatives Template'对象没有属性'encode