Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import socket
- import threading
- class Chat(object):
- UDP_IP="172.19.7.255" #ip of our hostel
- UDP_PORT_SEND=1100 # port number - u can use any num from 1000 to hz, I used till 10000
- UDP_PORT = 1100
- def __init__(self):
- self.sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) #create socket with defaul params for UDP
- self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 2) #allow to reuse addres
- self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 2) #allow broadcast
- #self.sock.setblocking(False)# without it also work and i dont know what that line do
- self.sock.bind( ('',self.UDP_PORT) ) #we binding to that port, so we catch all messages coming to this port
- def reg(self): #func for get user name
- print 'input your name:'
- name = raw_input()
- return name
- def getMessage(self): # func for catching messages.
- while True:
- try:
- data, addr = self.sock.recvfrom( 1024 ) #get data from binding socket with 1024 bytes size
- if not data is None:
- lock = threading.Lock()#creating critical section for console, output should be correct
- with lock:
- print data
- except: pass
- def run(self):
- self.name = self.reg()#get user name
- t = threading.Thread(target=self.getMessage)# creating new thread, in which we runing getMessage
- t.start() #starting thread
- while True: #inf cycle, when ENTER pressed, new message with go to self.UDP_PORT_SEND, in that app self.UDP_SEND ==
- print 'Input message:'
- message = raw_input()#get message
- self.sock.sendto( "{} > {}".format(self.name, message), (self.UDP_IP, self.UDP_PORT_SEND) ) #send message in UDP_IF to port == UDP_PORT_SEND
- threading._sleep(0.1) #main thread sleeping, for creating delay, in what print 'Input message:' creating after new message come КОСТЫЛЬ))
- c = Chat()
- print c.sock
- c.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement