0

我是套接字编程的新手,我正在尝试为也充当服务器的客户端编写一个 python 程序。我需要 1 个代码中的 2 个侦听 TCP 服务器。

客户端部分循环 5 次以创建 5 个客户端实例。

服务器部分应该同时监听 50 个客户端。

虽然我能够在同一代码中创建客户端和 1 个服务器,但第二个服务器无法连接。

如果有人可以帮助我,我将不胜感激。

我附上下面的代码。

import socket

count = 1
port1 = 12345
x=range(5)
for n in x:
    ClientSocket = socket.socket()
    host = '127.0.0.1'
    port = 1233
    print('Waiting for connection here')
    try:
        ClientSocket.bind(('',port1))
        ClientSocket.connect((host, port))
    except socket.error as e:
        print(str(e))

    Response = ClientSocket.recv(1024)

    Input = 'ServerMini'+str(count)
    ClientSocket.send(str.encode(Input))
    Response1 = ClientSocket.recv(1024)
    print(Response.decode('utf-8'))
    print(Response1.decode('utf-8'))
    ClientSocket.close()
    port1 = port1+1
    count = count+1
ClientSocket.close()

import os
from _thread import *

ServerSocket = socket.socket()
host = '127.0.0.1'
port = 12345
porta = 12346
ThreadCount = 0
try:
    ServerSocket.bind((host, port))
except socket.error as e:
    print(str(e))

print('Waitiing for a Connection..')
ServerSocket.listen(5)


def threaded_client(connection):
    connection.send(str.encode('Welcome to the Servern'))
#     while True:
    data = connection.recv(2048)
    print (data)
    print (port)
    reply = 'Server1 Says: ' + data.decode('utf-8') + 'connected' + '12345'
#         if not data:
#             break
    connection.sendall(str.encode(reply))
    connection.close()

x=range(50)
for n in x:
    while True:
        Client, address = ServerSocket.accept()
        print('Connected to: ' + address[0] + ':' + str(address[1]))
        start_new_thread(threaded_client, (Client, ))
        ThreadCount += 1
        print('Thread Number: ' + str(ThreadCount))
    ServerSocket.close()
    
    
# import os
# from _thread import *

# ServerSocket = socket.socket()
# host = '127.0.0.1'
# port = 12346
# ThreadCount = 0
try:
    ServerSocket.bind((host, porta))
except socket.error as e:
    print(str(e))

print('Waitiing for a Connection..')
ServerSocket.listen(5)


def threaded_client(connection):
    connection.send(str.encode('Welcome to the Servern'))
#     while True:
    data = connection.recv(2048)
    print (data)
    print (port)
    reply = 'Server2 Says: ' + data.decode('utf-8') + 'connected' + '12345'
#         if not data:
#             break
    connection.sendall(str.encode(reply))
    connection.close()

x=range(50)
for n in x:
    while True:
        Client, address = ServerSocket.accept()
        print('Connected to: ' + address[0] + ':' + str(address[1]))
        start_new_thread(threaded_client, (Client, ))
        ThreadCount += 1
        print('Thread Number: ' + str(ThreadCount))
    ServerSocket.close()
4

0 回答 0