Программирование нескольких клиентских сокетов - PullRequest
0 голосов
/ 19 июня 2020

Я пытаюсь создать многопоточную программу с несколькими клиентами. Когда клиент подключился, он покажет идентификатор клиента. Клиент может ввести exit, чтобы покинуть соединение, и всякий раз, когда клиент уходит, другой идентификатор клиента будет обновлен.

Это мой код сервера:

import socket
import os
from _thread import *

ServerSocket = socket.socket()
host = ''
port = 1233
ThreadCount = 0
all_connections = []
all_address = []

try:
    ServerSocket.bind((host, port))
except socket.error as e:
    print(str(e))

for c in all_connections:
    c.close()

del all_connections[:]
del all_address[:]
print('Waitiing for a Connection..')
ServerSocket.listen(5)


def threaded_client(connection):
    connection.send(str.encode('Welcome to the Server\n'))
    global ThreadCount
    connection.sendall(str.encode(str(ThreadCount)))

    while True:
        data = connection.recv(2048)
        data1 = data.decode('utf-8')
        if (data1 == "exit"):
            ThreadCount = ThreadCount - 1
            Client = str(connection.recv(1024), "utf-8")
            i=int(Client)-1
            del all_connections[i]
            del all_address[i]
            for conn in all_connections:
                conn.send(str.encode(str(Client)))
            print("One Client is left" + " | Current Amount Client: " + str(ThreadCount))
            break
        else:
            connection.sendall(str.encode("50"))
    connection.close()

while True:
    Client, address = ServerSocket.accept()
    all_connections.append(Client)
    all_address.append(address)
    start_new_thread(threaded_client, (Client,))
    ThreadCount += 1
    print('Connected to: ' + address[0] + ':' + str(address[1]) + " | Thread: " + str(ThreadCount) + " | Client: " + str(ThreadCount))

ServerSocket.close()

Это мой код клиента:

import socket

ClientSocket = socket.socket()
hostname = socket.gethostname()
host = socket.gethostbyname(hostname)
port = 1233

print('Waiting for connection')
try:
    ClientSocket.connect((host, port))
except socket.error as e:
    print(str(e))

Response = ClientSocket.recv(1024)
print(Response.decode('utf-8'))
ClientNombor = str(ClientSocket.recv(1024), "utf-8")
ClientNombor = int(ClientNombor)
print("You are Client:" + str(ClientNombor))
while True:
    print("Type 'Exit' To Leave or Type 'Hello I am Client' to know your Client ID")
    Input = input('-->: ')
    Input = Input.lower()
    ClientSocket.send(str.encode(Input))
    if (Input == "exit"):
        print("You will exit now")
        ClientSocket.send(str.encode(str(ClientNombor)))
        break
    elif (Input == "hello i am client"):
        print("You are Client:" + str(ClientNombor))
    else:
        print("Wrong Input Inserted")
    exitClientID = int(str(ClientSocket.recv(1024), "utf-8"))
    print(str(exitClientID))
    if (exitClientID != 50):
        if (ClientNombor>(exitClientID)):

            ClientNombor=ClientNombor-1
        print("One Client is Left, You are now Client:" + str(ClientNombor))


ClientSocket.close()

У меня три клиента, и это ответы. enter image description here enter image description here enter image description here

Сначала Клиент 1 завершает работу, и клиент 2 становится клиентом 1 и клиент 3 становится клиентом 2 . Затем клиент 1 снова выходит, и, предположительно, клиент 2 получает идентификатор клиента 1, чтобы показать 1, но почему он показывает «501» и приводит к тому, что клиент 2 не изменил идентификатор клиента. Кто-нибудь может помочь? Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...