如何从客户端套接字获取信息并在服务器上显示信息?

How to get information from a client socket and display information on a server?

如何强制服务器从客户端接收消息并显示消息:“{name} 发送消息:{data}”?例如,一个用户向另一个用户发送消息,当一个名为 John 的用户发送消息“Hello Alice, how are you?”时,此时服务器会显示 - John 将发送一条消息:Hello Alice, how你是?我会很感激你的帮助。 我希望能在本文中找到这个问题的答案。代码如下:

服务器:

import threading
import socket

HOST = '127.0.0.1'
PORT = 8888

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

server.listen(15)
print(f'Server {HOST}:{PORT} start.')

users = []

def send_all(data):
    for user in users:
        user.send(data)

def listen_user(user):
    print('Listening user')
    
    while True:
        data = user.recv(1024)
        print(f'User sent {data}')

        send_all(data)

def start_server():
    while True:
        user_socket, addr = server.accept()
        users.append(user_socket)

        potok_info = threading.Thread(target=listen_user, args=(user_socket,))
        potok_info.start()


if __name__ == '__main__':
    start_server()

客户:

import socket
import time
import threading
import os

HOST = '127.0.0.1'
PORT = 8888

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))


def send_message():
    print('Enter name: ')
    name = input()
    while True:
        data = client.recv(1024)
        print(data.decode('utf-8'))
        msg = (f'{name} send message {data}')
        client.send(msg.encode('utf-8')) # this
        
        
def send_server():
    
    listen_thread = threading.Thread(target=send_message)
    listen_thread.start()

    while True:
        client.send(input('you: ').encode('utf-8'))

        

if __name__ == '__main__':
    os.system('clear')
    print('***** Welcome in Security Chat. *****')
    send_server()

我修改了你的代码。

这是您的服务器脚本。

import threading
import socket

HOST = '127.0.0.1'
PORT = 8888

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))

server.listen(15)
print(f'Server {HOST}:{PORT} start.')

users = [] # To store their name
sort = [] # To store their socket

def listen_user(user):
    print('Listening user')
    sort.append(user)  # Store their socket in sort[]
    user.send('Name'.encode('utf-8')) # send 'Name' to clients
    name = user.recv(1024).decode('utf-8') # Receive their name
    users.append(name) # Store their name in user[]

    while True:
        data = user.recv(1024).decode('utf-8')
        print(f'{name} sent {data}')

        for i in sort: # Send received messages to clients
           if(i != server and i != user): # Filter server and message sender. Send message except them.
               i.sendall(f'{name} > {data}'.encode('utf-8'))
   
    user.close() # To close client socket connection.

def start_server():
    while True:
       user_socket, addr = server.accept()
       potok_info = threading.Thread(target=listen_user, args=(user_socket, ))
       potok_info.start()


if __name__ == '__main__':
    start_server()

这是您的客户端脚本,

import socket
import time
import threading
import os

HOST = '127.0.0.1'
PORT = 8888

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

def send_message():

   if('Name' in client.recv(1024).decode('utf-8')): # If 'Name' received. It allows you to send the name.
       name  = input('Enter Name : ') # Type name
       client.send(name.encode('utf-8'))

   while True:
       data = input('Enter : ') # Enter message
       client.send(data.encode('utf-8'))
    
       receive = client.recv(1024).decode('utf-8')# Receive messages from other clients.
       print(receive)

def send_server():

   listen_thread = threading.Thread(target=send_message)
   listen_thread.start()      

if __name__ == '__main__':
   os.system('clear')
   print('***** Welcome in Security Chat. *****')
   send_server()

添加删除代码中的某些部分。仔细研究它,然后您可以识别代码中的错误。