I have been experimenting with network programing with python. To teach myself how to do this I have been playing with multiple versions of TCP chat servers and clients. My newest attempt has left me wondering what is wrong with the code I have just written. Only when a message has been sent from the client I have just created, does the other messages come in. I am not sure why this is happening. I have been searching online and I can't figure out why it is happening. All I do know is that it is not the servers mistake. I am certain that the problem is with the client I just created.
import socket, thread, threading, os
def sendMsg():
Message = raw_input('[-]You:')
s.send(Message)
def recvMsg():
data = s.recv(buff)
print(data)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input('[-]Target Ip-> ')
port = 5000
buff = 1024
try:
s.connect((host, port))
except:
print('[-]Failed to Connect')
s.close()
loop = True
threads = []
while loop == True:
try:
t1 = threading.Thread(target=sendMsg())
threads.append(t1)
t1.start()
t2 = threading.Thread(target=recvMsg())
threads.append(t2)
t2.start()
except KeyboardInterrupt:
print('\n')
break
s.close()
os.system('clear')
Server code
# Tcp Chat server
import socket, select, os, time
def broadcast_data (sock, message):
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
socket.close()
CONNECTION_LIST.remove(socket)
if __name__ == "__main__":
CONNECTION_LIST = []
RECV_BUFFER = 4096
IP_MNG = ''
PORT = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP_MNG, PORT))
server_socket.listen(10)
CONNECTION_LIST.append(server_socket)
print "[-]Connected To " + str(PORT)
start = True
while start == True:
try:
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
if sock == server_socket:
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print "Client (%s, %s) connected" % addr
broadcast_data(sockfd, "[-][%s:%s] entered room\n" % addr)
else:
try:
data = sock.recv(RECV_BUFFER)
if data:
broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue
except KeyboardInterrupt:
print('[-]Server Stopped')
start = False
server_socket.close()
time.sleep(1)
os.system('clear')