0

I have started to make my own TCP server and client. I was able to get the server and the client to connect over my LAN network. But when I try to have another client connect to make a three way connection, it does not work. What will happen is only when the first connected client has terminated the connection between, the server and the client, can the other client connect and start the chat session. I do not understand why this happens. I have tried threading, loops, and everything else I can think of. I would appreciate any advice. I feel like there is just one small thing i am missing and I can not figure out what it is.

Here is my server:

import socket
from threading import Thread 

def whatBeip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 0))  
    local_ip_address = s.getsockname()[0]
    print('Current Local ip: ' + str(local_ip_address))

def clietConnect():
    conn, addr = s.accept()
    print 'Connection address:', addr
    i = True
    while i == True:
        data = conn.recv(BUFFER_SIZE)
        if not data:
            break 
        print('IM Recieved: ' + data)
        conn.sendall(data)  # echo


whatBeip()    

TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 1024
peopleIn = 4

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(peopleIn)

for client in range(peopleIn):
    Thread(target=clietConnect()).start() 


conn.close()

Here is my client

import socket


TCP_IP = '10.255.255.3'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))

i = True
while i == True:
    s.sendall(raw_input('Type IM: '))
    data = s.recv(BUFFER_SIZE)

s.close()

1 Answers1

0

This is your main problem: Thread(target=clietConnect()).start() executes the function clientConnect and uses it's return value as the Thread function (which is None, so the Thread does nothing)

Also have a look at:

1) You should wait for all connections to close instead of conn.close() in the end of the server:

threads = list()
for client in range(peopleIn):
    t = Thread(target=clietConnect)
    t.start() 
    threads.append(t)
for t in threads: t.join()

and to close the connection when no data is received:

    if not data:
        conn.close()
        return

2) You probably want to use SO_REUSEADDR [ Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems? , Python: Binding Socket: "Address already in use" ]

3) And have a look at asyncio for python

Community
  • 1
  • 1
Augusto Hack
  • 2,032
  • 18
  • 35