I am completely new to network and socket programming. I have tried some code; say I have 3 clients and a server c1 messages and it goes through server and reflected in c2 and c3.
My problem:
- I don't want to see my own message (if I say "hi" it's showing for me also but it should be shown in c2 and c3 only).
- is there a way like only c2 can see a message and not c3 when c1 sends it
- unable to do this in Python and error is shown, so how can be it done in Python 3
server.py
import socket
import time
host = ''
port = 5020
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
a=s.bind((host, port))
#s.setblocking(0)
quitting = False
print "Server Started."
print("socket binded to %s" % (port))
while not quitting:
try:
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
#print clients
for client in clients:
if not a:# tried this for broadcasting to others not c1
s.sendto(data, client)
print time.ctime(time.time()) + str(addr) + ": :" + str(data)
except:
pass
s.close()
This is Python 2 code.
client.py
enter code hereimport socket
import threading
import time
shutdown = False
def receving(name, sock):
while not shutdown:
try:
while True:
data, addr = sock.recvfrom(1024)
print str(data)
except:
pass
host = ''
port = 5020
server = ('',5020)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
#s.setblocking(0)
for i in range(5):
threading.Thread(target=receving, args=("RecvThread",s)).start()
alias = raw_input("Name: ")
message = raw_input(alias + "-> ")
while message != 'q':
if message != '':
s.sendto(alias + ": " + message, server)
message = raw_input(alias + "-> ")
time.sleep(0.1)
shutdown = True
s.close()
The output am getting in server is correct the time and server message, but my problem is client output c1 message is shown in c1 itself.
Name: c1
c1-> hi
c1-> c1: hi
see the 3rd line the message "hi" is shown to me also.