Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1.  
  2. import socket
  3. import threading
  4.  
  5. class Chat(object):
  6.  
  7. UDP_IP="172.19.7.255" #ip of our hostel
  8. UDP_PORT_SEND=1100 # port number - u can use any num from 1000 to hz, I used till 10000
  9. UDP_PORT = 1100
  10.  
  11. def __init__(self):
  12. self.sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) #create socket with defaul params for UDP
  13. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 2) #allow to reuse addres
  14. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 2) #allow broadcast
  15. #self.sock.setblocking(False)# without it also work and i dont know what that line do
  16. self.sock.bind( ('',self.UDP_PORT) ) #we binding to that port, so we catch all messages coming to this port
  17.  
  18. def reg(self): #func for get user name
  19. print 'input your name:'
  20. name = raw_input()
  21. return name
  22.  
  23. def getMessage(self): # func for catching messages.
  24. while True:
  25. try:
  26. data, addr = self.sock.recvfrom( 1024 ) #get data from binding socket with 1024 bytes size
  27. if not data is None:
  28. lock = threading.Lock()#creating critical section for console, output should be correct
  29. with lock:
  30. print data
  31. except: pass
  32.  
  33. def run(self):
  34. self.name = self.reg()#get user name
  35. t = threading.Thread(target=self.getMessage)# creating new thread, in which we runing getMessage
  36. t.start() #starting thread
  37. while True: #inf cycle, when ENTER pressed, new message with go to self.UDP_PORT_SEND, in that app self.UDP_SEND ==
  38. print 'Input message:'
  39. message = raw_input()#get message
  40. self.sock.sendto( "{} > {}".format(self.name, message), (self.UDP_IP, self.UDP_PORT_SEND) ) #send message in UDP_IF to port == UDP_PORT_SEND
  41. threading._sleep(0.1) #main thread sleeping, for creating delay, in what print 'Input message:' creating after new message come КОСТЫЛЬ))
  42.  
  43. c = Chat()
  44. print c.sock
  45. c.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement