python – 两个客户端无法成功连接到服务器

我想添加一个功能,其中两个客户端可以不停地发送给彼此的消息,而无需等待.

我有一个服务器的脚本:

import socket
import threading
from datetime import datetime
from random import randint

global num
num = 0

class serverThread(threading.Thread):
    def __init__(self, client, address):
        global num
        num = num + 1
        self.id = num
        threading.Thread.__init__(self)
        self.client = client
        self.address = address
        print "serverThread init finished-" + str(self.id)

    def run(self):
        print "r1 num-" + str(self.id)
        size = 1024
        while True:
            #try:
                print "r2*************-" + str(self.id)
                data = self.client.recv(size)
                print "r3..... " + data
                print "r4-" + str(self.id)
                if data:
                    print "r5-" + str(self.id)
                    response = data

                    self.client.send(response)
                    print "r6-" + str(self.id)
                else:
                    print "r7-" + str(self.id)
                    raise Exception('Client disconnected-' + str(self.id) )
            #except:
               # print "Except"
               # self.client.close()
               # return

def create(ipHost, port):
    server = socket.socket()
    server.bind((ipHost, port))
    print "The server was created successfully."
    return server

def listen(server):
    server.listen(5)
    client, address = server.accept()
    c1 = serverThread(client, address)
    c1.start()
    client, address = server.accept()
    c2 = serverThread(client, address)
    c2.start()
    print "finished both threads created"

    while c1.isAlive() and c2.isAlive():
        continue

server = create("0.0.0.0", 1725)
listen(server)

你可以看到我没有使用try,除非因为我不知道如何使用它们.

我的第二个脚本,客户端:

import socket
import threading

class sendThread(threading.Thread):
    def __init__(self, ip, port):
        threading.Thread.__init__(self)
        self.client = socket.socket()
        self.port = port
        self.ip = ip
        self.client.connect((self.ip, self.port))
        print "[+] New send thread started for "+ip+":"+str(port) + "...Everything went successful!"

    def run(self):
        while True:
            data = raw_input("Enter command:")
            self.client.send("Client sent: " + data)

class receiveThread(threading.Thread):
    def __init__(self, ip, port):
        threading.Thread.__init__(self)
        self.client = socket.socket()
        self.ip = ip
        self.port = port
        self.client.connect((str(self.ip), self.port))
        print "[+] New receive thread started for "+ip+":"+str(port) + "...Everything went successful!"

    def run(self):
        print "Entered run method"
        size = 1024
        while True:
            data = self.client.recv(size)
            if data != "" or data:
                print "A client sent " + data
def client():
    port = 1725
    ip = '127.0.0.1'
    print "Connection from : "+ip+":"+str(port)

    receive = receiveThread(ip, port)
    print "b1"
    receive.start()
    print "b2"
    send = sendThread(ip, port)
    print "b3"
    send.start()
    while send.isAlive() and receive.isAlive():
        continue
    print "-----END of While TRUE------"
    print "Client disconnected..."

client()

我认为描述我的脚本是一个好主意,在我的代码中一步一步地进行,也许它有所帮助,因此它更具可读性.

问题

当我想在运行两个客户端之前运行服务器时,它会打印出来

The server was created successfully.

我运行2个客户端,两个客户端打印:

Connection from : 127.0.0.1:1720
[+] New receive thread started for 127.0.0.1:1720...Everything went successful!
b1
Entered run method
b2
[+] New send thread started for 127.0.0.1:1720...Everything went successful!
b3
Enter command:

但是,创建的第二个客户端与服务器之间的连接存在问题.我写了一个代码,所以当服务器收到客户端发送的消息时,它会将消息打印为服务器中的输出.但是,当第一个客户端发送消息时,它会打印它.但不是第二个客户发送时.

我甚至尝试复制客户端脚本并将其放在一个新文件中,因此这两个客户端来自两个不同的文件,可能会发现问题.但是,它没有帮助.我试图运行第一个文件,然后运行第二个文件,反之亦然.第二个客户端始终遇到服务器问题. (顺便说一句,我还想知道为什么客户端文件不打印他自己发送的消息(他仍将从服务器接收它)但这是次要问题).

如果您告诉代码中的问题,我会更高兴,而不是给我一个您创建或找到的问题!但这两种方法都有效.

最佳答案
您正在为每个客户端创建两个连接,一个用于接收,另一个用于发送.您的服务器正好需要两个连接,即来自第一个客户端的两个连接.每个客户端只创建一个连接:

import socket
import threading

def receive_loop(client):
    print "Entered receive_loop method"
    while True:
        data = client.recv(1024)
        if not data:
            break
        print "A client sent " + data

def main():
    port = 1725
    ip = '127.0.0.1'
    print "Connection from : %s:%s" % (ip, port)
    client = socket.socket()
    client.connect((ip, port))
    receive = threading.Thread(target=receive_loop, args=(client,))
    receive.start()
    while True:
        data = raw_input("Enter command:")
        client.send("Client sent: " + data)

if __name__ == '__main__':
    main()

转载注明原文:python – 两个客户端无法成功连接到服务器 - 代码日志