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

时间:2019-02-10 21:01:26

标签: python sockets send recv

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

Server.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("")

Client.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("")

3 个答案:

答案 0 :(得分:2)

  

CaSper给了我服务器代码,多个客户端可以连接到服务器,但是现在的问题是客户端无法彼此对话...

这主要是因为您的客户想要s_name = s.recv(1024),而CaSper的服务器未发送其名称。这是您的客户端的一种变体(期望 host port 作为命令参数),可以与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

  

...您是否可以更改我的服务器以使其正常工作...

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

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("")

答案 1 :(得分:0)

也许您尝试使用线程模块或时间模块。这是因为两个脚本都在同一时间发送消息。尝试Ex(客户端从服务器首先发送等待消息,然后客户端向服务器发送消息)。

答案 2 :(得分:-2)

此服务器

import socket
import threading as th

def accept_client():
    while True:
        # ACCEPTING    
        cli_sock, cli_add = ser_sock.accept()
        uname = cli_sock.recv(1024)
        CONN_LIST.append((uname, cli_sock))
        print('%s is now connected' %uname)

def broadcast_usr():
    while True:
        for i in range(len(CONN_LIST)):
            try:
                data = CONN_LIST[i][1].recv(1024)
                if data:
                    b_usr(CONN_LIST[i][1], CONN_LIST[i][0], data)
            except Exception as x:
                print(x.message)
                break

def b_usr(cs_sock, sen_name, msg):
    for i in range(len(CONNECTION_LIST)):
        if (CONN_LIST[i][1] != cs_sock):
            CONN_LIST[i][1].send(sen_name)
            CONN_LIST[i][1].send(msg)


if __name__ == "__main__":    
    CONN_LIST = []

    # SOCKET
    ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # BINDING
    host = '192.168.x.x' #LOCAL HOST
    port = 4444
    ser_sock.bind((host, port))

    # LISTENING    
    ser_sock.listen(1)
    print('Chat server started on port : ' + str(port))

    thread_ac = th.Thread(target = accept_client)
    thread_ac.start()

    thread_bs = th.Thread(target = broadcast_usr)
    thread_bs.start()