Two clients don't connect successfully to the

2019-05-07 08:07发布

I want to add a feature where two clients can send to each other messages without stop and without the need of waiting.

I have a script of the server:

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)

As you can see I'm not using try and except because I don't know good how to use them.

My second script, the client:

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

I thought it would be a good idea to describe my scripts, go step by step in my code, maybe it helps so it will be more readable.

Problem

When I want to run the server before running the two clients it prints

The server was created successfully.

I run 2 clients and both clients print:

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:

However, there is a problem in the connection between the second client created and the server. I wrote a code so when the server receives a message sent by a client, it will print the message as output in the server. However, when the first client sends a message it prints it. But not when the second client sends.

I even tried to copy the client script and put it in a new file, so the two clients are from two different files and maybe find a problem. However, it didn't help. I tried to run the first file and then the second file, and vice versa. Always the second client had a problem with the server. (By the way, I would also want to know why the client file doesn't print the message he himself sends (he will still receive it from the server) but that's a secondary problem).

I would be even happier if you tell what is the problem in the code, instead of giving me one that you created or find! But both methods work.

1条回答
Melony?
2楼-- · 2019-05-07 08:45

You are creating two connections per client, one for receiving and one for sending. Your server expects exactly two connections, i.e. the two from the first client. Create only one connection per client:

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()
查看更多
登录 后发表回答