Question

I've tried looking about for an answer but I can't seem to find one that answers my specific problem.

Perhaps I don't know how to articulate the problem correctly.

I think I've pinpointed what it is, but the thing is I just don't know how to fix it.

EDIT: I was trying to use two clients on one TCP Socket. Can't do that. I'll have to think of another way. Solved, I guess.

So what I've got is are

1: Two Clients

2: One Server

The objective is this: Have the server distribute new usernames to all the clients as they connect.

This is what happens when I run the program:

Server: Define Host, and Port, initialize it. Check

Client 1: Connects to the server. Check

Client 1: Once connected, sends a string to the server. Check

Server: Receives a string, checks if the string is in a list is created. If it is: Pass, if it's not, send to everyone the new string. Check

Client 1: [Now waiting to receive data] Recieves data, checks if the string received matches the one it sent. If it does, print("It's one of ours!"), else, make the new string = to Client 2 Username. Check

Client 2: Connects to server: Check

Server: [If it receives a string, prints it.] (Works) Checks if the new string is in the list. [It isn't] So It sends the new username to everyone, and then prints ("Sent to everyone") Check

But, when client 2 receives the string, it prints it. However, client 1 never recives the string.

And when running client one in IDLE, I noticed something went wrong as Client 1 tried to receive the data. (The while loop that the data = s.recv began looping real fast, instead of waiting)

I've asked around in chat, but it seems nobody's around right now. I've tried looking this up but I really can't find an answer. What I suspect is happening is that when my server sends to 'connection' the second time, it somehow overrides the original client connection.

Here's my server code:

from socket import *
import threading
import os
import csv

Username_List = []

host = input("Host: ")
port = input("Port: ")

ss = socket(AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
ss.listen(2)




while True:
    try:
        connection,address = ss.accept()
        data = connection.recv(1024)
        if data:
            translated_data = data.decode()
            print(translated_data)

            if translated_data in Username_List:
                pass
            else:
                Username_List.append(translated_data)
                connection.sendall(translated_data.encode())
                print("Sent new username to everyone")
    except IOError:
        connection.close()
        print("An exception with a connected user occured")
        break

And here is my client code: [The only difference between client 1 and 2 is I changed the username variable]

# Sample Username Client Service Handler.
from socket import *
import threading
import os
import csv

Username = ("Owatch")
host = input("Host: ")
port = input("Port: ")
try:

    ss = socket(AF_INET,SOCK_STREAM)
    ss.connect((host,int(port)))
except IOError:
    print("Aw no man")

ss.send(Username.encode())

while True:
    try:
        print("Waiting to Recieve Data")
        data = ss.recv(1024)
        if data:
            translated_data = data.decode()
            print(translated_data)
            if translated_data == Username:
                print("It's one of ours!")

            else:
                Client_Username = translated_data
                print (Client_Username)


    except Exception as e:
        print (vars(e))

If you could please help I'd be grateful.

If you know of an answer to my question that's already been asked, please tell me and I'll remove this post to avoid breaking rules. Thanks!

Was it helpful?

Solution

Right then I started with what you had then changed it till it worked what I've done is created a client class which starts a thread with each connection and adds it to a list of threads (please if I'm doing something horribly wrong smarter people correct me), the thread runs gets some data checks if that's in the list of user names if its not sends out a message to all the clients in the thread list with that name then the thread just chills out. Anyway on to the code.

SERVER!!!

import csv

class client(threading.Thread):
    Username_List = []
    def __init__(self, conn):
        super(client, self).__init__()
        self.conn = conn

    def run(self):
        print "Client thread started"
        data = self.conn.recv(1024)
        print "Received: {0}".format(data)
        if data in client.Username_List:
            self.send_msg("Welcome Back!")
        else:
            for cnt in threadz:
                cnt.send_msg(data)
            print("Sent new username to everyone")
            client.Username_List.append(data)
        while True:
            # dont need nothing now
            pass

    def send_msg(self,msg):
        self.conn.send(msg)

host = input("Host: ")
port = input("Port: ")

ss = socket() #AF_INET,SOCK_STREAM)
ss.bind((host,int(port)))
print "Server Opening on port: {0}".format(port)
ss.listen(2)
threadz = []
print "Begining Wait for connections"

while True:      
    try:
        connection, address = ss.accept()
        print "Got ONE!"
        c = client(connection)
        print "Recevied connection from:{0} On port:{1}".format(address[0],address[1])
        c.start()
        threadz.append(c)
        print "Client appended to threadz, currently {0} threadz active".format(len(threadz))

    except IOError,KeyboardInterrupt:
        connection.close()
        print("An exception with a connected user occured")
        break

The CLIENT:

# Sample Username Client Service Handler.
from socket import *
import threading
import os
import csv

Username = ("ShyGuy")
host = input("Host: ")
port = input("Port: ")
try:
    ss = socket() #AF_INET,SOCK_STREAM)
    ss.connect((host,int(port))) #I was using ("localhost",1234) for testing
    ss.send(Username)
except IOError:
    print("Aw no man")


print("Waiting to Recieve Data")
while True:
    try:
        data = ss.recv(1024)
        if data:
            translated_data = data.decode()
            print(translated_data)
            if translated_data == Username:
                print"Name: {0} has been registered on server!".format(translated_data)
            else:
                Client_Username = translated_data
                print "New client name received: {0}".format(Client_Username)


    except Exception as e:
        print (vars(e))

That works on python 2.7 with two clients locally. Needs to use a semaphore to stop the threads printing at the same time as the main server loop prints: http://en.wikipedia.org/wiki/Semaphore_(programming)

This code does nothing graceful with client disconnects, but once you can work with the exceptions that a raised when that happens I'm sure you'll learn some more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top