Пример #1
0
def get_friends_chat_history():
    for friend in friends:
        try:
            header = str(PRIVATE_INIT) + User + "\r\n" + friend
            method.send(sock, header, )
        except Exception as e:
            print("private chat page init error ", e)
            # messagebox.showerror('Error','Private ChatPage initialize error!')

        try:
            data, rest = method.receive(sock)
            msg_type = data[:3]
            print(msg_type)
            user1, user2 = data[3:].split("\r\n")
            if msg_type == str(PRIVATE_INIT_SUCCESS):
                lists = rest.split("\r\n")
                #assert user1 == User
                chat_list = []
                for list in lists:
                    chat_list.append(list.split("\t"))
                user2room_history[user2] = chat_list

            elif msg_type == str(PRIVATE_INIT_NONE):
                user2room_history[user2] = []

            elif msg_type == str(PRIVATE_INIT_ERROR):
                user2room_history[user2] = []
                messagebox.showerror('Error',"Fetch chat history with "+user2+" error!")

        except Exception as e:
            print("receive friends chat history error:",e)
Пример #2
0
 def login(self):
     user = self.username.get()
     pwd = self.password.get()
     print(pwd)
     if not user:
         messagebox.showerror('Error',"用户名不能为空")
         #self.pwdE.delete(0, END)
         self.password.set("")
         return
     if not pwd:
         messagebox.showerror('Error',"密码不能为空")
         #self.pwdE.delete(0, END)
         self.password.set("")
         return
         
     msg=str(LOGIN)+user+"\r\n"+pwd
     #self.sock.send(bytes(msg,encoding='utf-8'))
     method.send(self.sock,msg)
     try:
         #receive= self.sock.recv(1024).decode()
         receive,_=method.receive(self.sock)
     except Exception as e:
         print(e)    
         messagebox.showerror('Error',"连接失败,请关闭重连!")
     
     print(receive)
     if receive==str(LOGIN_SUCCESS):
         self.flag=user
         messagebox.showinfo('Info',"登陆成功")
         self.master.destroy()
     elif receive==str(LOGIN_WRONG):
         messagebox.showerror('Error',"用户名不存在或密码错误")
     elif receive==str(LOGIN_REPEAT):
         messagebox.showerror('Error',"该用户已经登陆!")
Пример #3
0
def get_chat_history(sock,user):
    header = str(GET_ALL_CHAT_HISTORY)
    msg = user.encode("utf-8")
    method.send(sock,header,msg)

    try:
        data, rest = method.receive(sock)
    except Exception as e:
        messagebox.showerror('Error','Get chat history error!')
        print('get chat history error',e)
        return

    state = data[:3]
    if state == str(RET_HISTORY_ERROR):
        messagebox.showerror('Error','--Get chat history error!')
        return

    if state == str(RET_HISTORY_SUCCESS):
        msgs = rest.split("\r\n")
        count = 0
        for msg in msgs:
            detail = msg.split("\t")
            if len(detail)>=2 and count<5:
                name = detail[0]
                time = detail[1]
                content = detail[2]
                count += 1
                if name != user:
                    show_msg(name,content,'green',msg_time = time)
                else :
                    show_msg('<Me>',content,'blue',msg_time = time)
        return
Пример #4
0
def send_msg(conn, text, rest):
    try:
        sender = conn2user[conn]
        receiver, content_len = text.split("\r\n")
        content_len = int(content_len)
    except Exception as e:
        print("Wrong message", e)
        return str(WRONG_MESSAGE)

    try:
        content = method.receive(conn, content_len - len(rest))
        content = rest + content
        if len(content) != content_len:
            return "{0}{1}".format(str(SENDMSG_ERROR), receiver)
    except Exception as e:
        print("Wrong text", e)
        return "{0}{1}".format(str(SENDMSG_ERROR), receiver)

    if len(receiver) == 0:
        broadcast_data(conn,
                       "{0}{1}\r\n{2}".format(SEND_ALL, sender, content_len),
                       addition=content)
    else:
        corres = user2conn.get(receiver)
        if corres is None:
            print("NO")
            #conn.send(bytes(str(SEND_NONE)+receiver,encoding="utf-8"))
            Msg = str(SEND_NONE) + receiver
            return Msg
        #corres.send(bytes("%3d%2d%s%4d%s"%(SEND_PER,len(sender),sender,len_content,content),encoding="utf-8"))
        Msg = "{0}{1}\r\n{2}".format(SEND_PER, sender, content_len)
        method.send(corres, Msg, content)

    return None
Пример #5
0
def get_all_friends():
    try:
        msg = User.encode("utf-8")
        method.send(sock,str(SHOW_ALL_FRIENDS),msg)
    except Exception as e:
        print("get friends error ",e)

    try:
        data,rest = method.receive(sock)
    except Exception as e:
        print("receive friends error, ",e)

    friends = []

    if data[:3] == str(SHOW_FRIENDS_SUCCESS):
        friends = rest.split("\r\n")
        return friends

    if data[:3] == str(SHOW_FRIENDS_ERROR):
        print("server get friends error")

    if data[:3] == str(NO_FRIENDS):
        print(User+" have no friends at this time ")


    return friends
Пример #6
0
def send_add_friend_request():
    header = str(ADD_FRIEND)
    name_ = friend_name.get()
    msg = User + "\r\n" + name_
    msg = msg.encode("utf-8")
    try:
        method.send(sock,header,msg)
    except Exception as e:
        print("!!Send add-friend-request error:",e)
Пример #7
0
def download_file(event):
    #fileListbox.bind('<Double-Button-1>',download_file)
    choice = fileListbox.get(fileListbox.curselection())
    print("select: ",choice,type(choice),User)
    msg = User + "\r\n" + choice
    msg = msg.encode("utf-8")
    try:
        method.send(sock,str(DOWNFILE),msg)
    except Exception as e:
        print("send downfile request error ",e)
        messagebox.showerror('Error','Download file error!')
        return
Пример #8
0
    def send(self):
        text = self.text_msg.get('0.0',END)
        print("text ",text)
        if text is None or len(text)==0:
            return

        self.show_msg('<Me>',text,'blue')

        content = text.encode("utf-8")
        msg = str(SEND_MESSAGE) + self.receiver + "\r\n" + str(len(text))
        method.send(self.sock,msg,content)
        self.text_msg.delete('0.0',END)
Пример #9
0
def broadcast_data(sender, message, addition=b""):
    print("broadcast: ", message)
    for receiver in connections:
        if receiver != sock and receiver != sender and conn2user.get(
                receiver) is not None:
            print(receiver, conn2user.get(receiver))
            try:
                #receiver.sendall(message)
                method.send(receiver, message, addition)

            except Exception as e:
                print("broadcast error", e, receiver)
Пример #10
0
def send_emoji_4():
    emoji = "[emoji-hotpot]"
    header = str(SEND_EMOJI) + "" + "\r\n" + str(len(emoji))
    msg = emoji.encode("utf-8")
    try:
        method.send(sock, header, msg)
    except Exception as e:
        messagebox.showerror('Error', 'Send emoji error')
        print('error,', e)

    print("got this emoji", emoji)
    show_msg('<Me>', emoji, 'blue', is_file=False, msg_time=None)
Пример #11
0
def get_history_files():
    header = str(GET_ALL_FILE_HISTORY)
    method.send(sock,header)

    try:
        data,rest = method.receive(sock)
    except Exception as e:
        print("get history file errors")
        messagebox.showerror('Error','Get history files error!')
        return

    names = rest.split("\r\n")
    return names
Пример #12
0
def send_message():
    text = input_text.get('0.0','end')
    header = str(SEND_MESSAGE) + "\r\n" + str(len(text))

    if text is None:
        return
    try:
        send_text = text.encode("utf-8")
        method.send(sock,header,send_text)
        show_msg('<Me>',text,'blue',is_file = False)
    except Exception as e:
        messagebox.showerror('Error','Sending message error!')
        print('send msg error,',e)

    input_text.delete('0.0','end')
Пример #13
0
def send_all():
    print("Now: ", user_list)
    send_text = text_msg.get('0.0', END)
    if send_text is None:
        return
    if len(send_text) == 0:
        return

    show_msg("<我>", send_text, "green")

    content = send_text.encode("utf-8")
    Msg = "{0}{1}\r\n{2}".format(SENDMSG, "", len(content))
    method.send(sock, Msg, content)

    text_msg.delete('0.0', END)
Пример #14
0
def handle_download(conn, msg):
    try:
        #print("length:",len(msg.split("\r\n")),msg.encode())
        sender, loc, file_name = msg.split("\r\n")
        receiver = conn2user[conn]
    except Exception as e:
        print("Wrong info", e)
        return str(WRONG_MESSAGE)

    file_path = os.path.join("__{0}_{1}__".format(sender, loc), file_name)
    if os.path.exists(file_path) == False:
        return str(DOWNFILE_NONE)
    file_size = os.stat(file_path).st_size
    method.send(
        conn, "{0}{1}\r\n{2}".format(str(DOWNFILE_SUCCESS), file_name,
                                     file_size), method.read_file(file_path))
    return None
Пример #15
0
   def handle(self):
      print '...connected from:' , self.client_address
      self.data=self.rfile.readline().strip()
      if self.data:
         print self.data
         msg_split=self.data.split('+')
         if not cmp('pub',msg_split[0]):
            if cmp(HOST,msg_split[1]):
               NextIp=method.chooseNextNode(IPTABLE,msg_split[1])
	       method.send(NextIp,1111,self.data)
            else:
               index.storeGIndex((msg_split[2],msg_split[3]))
         if not cmp('test',self.data):
               self.wfile.write(str(HOST)+':Received')

         if not cmp('build',self.data):
               print 'good here'
               index.buildIndex()
Пример #16
0
    def send(self):
        send_text = self.text_msg.get('0.0', END)
        if send_text is None:
            return
        if len(send_text) == 0:
            return

        if self.state == False:
            messagebox.showerror('Error', "对方已下线!")
            return

        self.show_msg("<我>", send_text, "green")

        content = send_text.encode("utf-8")
        Msg = "{0}{1}\r\n{2}".format(SENDMSG, self.receiver, len(content))
        method.send(self.sock, Msg, content)

        self.text_msg.delete('0.0', END)
Пример #17
0
def ask_user_list(sock):
    msg = str(ASKUSERS)
    #sock.send(bytes(msg,encoding="utf-8"))
    method.send(sock, msg)
    lis = []
    try:
        data, rest = method.receive(sock)
        assert data[:3] == str(ASKUSERS_RET)
        lis_len = int(data[3:])
        print(lis_len)
        lis = method.receive(sock, lis_len - len(rest))
        lis = rest + lis
        assert len(lis) == lis_len
        lis = lis.decode("utf-8")
    except Exception as e:
        print(e)
        return None

    return lis.split("\r\n")
Пример #18
0
def handle_file(conn, msg, rest):
    try:
        #print("length:",len(msg.split("\r\n")),msg.encode())
        receiver, file_name, file_size = msg.split("\r\n")
        file_size = int(file_size)
        sender = conn2user[conn]
    except Exception as e:
        print("Wrong file info", e)
        return str(WRONG_MESSAGE)

    try:
        file_data = method.receive(conn, file_size - len(rest))
        file_data = rest + file_data
        if len(file_data) != file_size:
            return "{0}{1}".format(str(SENDFILE_ERROR), receiver)

    except Exception as e:
        print("Wrong file", e)
        return "{0}{1}".format(str(SENDFILE_ERROR), receiver)

    print("receive file: ", file_size, len(file_data))
    flip = "__{0}_{1}__".format(sender, receiver)
    if os.path.exists(flip) == False:
        os.makedirs(flip)
    path = os.path.join(flip, file_name)
    with open(path, "wb") as f:
        f.write(file_data)

    if len(receiver) == 0:
        broadcast_data(conn, "{0}{1}\r\n{2}".format(SENDFILE_ALL, sender,
                                                    file_name))
    else:
        corres = user2conn.get(receiver)
        if corres is None:
            print("NO")
            Msg = str(SENDFILE_NONE) + receiver
            method.send(conn, Msg)
            return

        Msg = "{0}{1}\r\n{2}".format(SENDFILE_PER, sender, file_name)
        method.send(corres, Msg)

    return str(SENDFILE_SUCCESS)
Пример #19
0
def get_users(sock,user):
    header = str(GET_ALL_USERS)

    method.send(sock,header)

    try:
        data, rest = method.receive(sock)
    except Exception as e:
        messagebox.showerror('Error','Get users error!')
        return None

    state = data
    if state == str(GET_SUCCESS):
        #rest = rest.decode("utf-8")
        users = rest.split("\r\n")
        print("find users: ")
        for user in users:
            print(user)
        return users
Пример #20
0
    def usrsign():
        user = str(ns.get())
        pwd = str(pwds.get())
        pwd1 = str(pwds1.get())
 
        if not user or len(user)==0 or user.find(" ")!=-1 or user.find("\t")!=-1:
            print("用户名不合法")
            messagebox.showerror('Error',"用户名不合法")
            return
        if pwd != pwd1:
            print("输入的两次密码不一致,请重新输入!")
            pwds.set("")
            pwds1.set("")
            messagebox.showerror('Error',"输入的两次密码不一致,请重新输入!")
            return
            
        msg=str(REGISTER)+user+"\r\n"+pwd
        #self.sock.send(bytes(msg,encoding='utf-8'))
        method.send(self.sock,msg)
        
        #data = self.sock.recv(1024).decode()
        try:
            data,_=method.receive(self.sock)
        except Exception as e:
            print(e)    
            messagebox.showerror('Error',"发送失败,请重试!")
        
        if data == str(REGISTER_SUCCESS):
            print("注册成功")
            messagebox.showinfo('Info',"注册成功")
            top2.destroy()
            return
        elif data == str(REGISTER_ERROR):
            print("用户名重复")
            messagebox.showerror('Error',"用户名已存在")
        return
Пример #21
0
def handle(conn, msg, rest):
    try:
        rtype = int(msg[0])
    except Exception as e:
        print("wrong request!", e)
        method.send(conn, str(WRONG_MESSAGE))
        return

    state = "None"
    if rtype == LOGIN:
        state = login(conn, msg[1:])

    elif rtype == REGISTER:
        state = register(conn, msg[1:])
        #print(state)

    elif rtype == SENDMSG:
        state = send_msg(conn, msg[1:], rest)
        if state is None:
            return

    elif rtype == LOGOUT:
        user = conn2user.get(conn)
        if user is not None:
            del user2conn[user]
            conn2user[conn] = None
            broadcast_data(conn, "{0}{1}".format(LOGOUT_INFO, user))
        return

    elif rtype == ASKUSERS:
        lis = list(user2conn.keys())
        msg = "\r\n".join(lis)
        msg = msg.encode("utf-8")
        header = str(ASKUSERS_RET) + str(len(msg))
        method.send(conn, header, msg)
        print(msg)
        return

    elif rtype == SENDFILE:
        state = handle_file(conn, msg[1:], rest)

    elif rtype == DOWNFILE:
        state = handle_download(conn, msg[1:])
        if state is None:
            return

    print(rtype, state)
    #conn.sendall(bytes(state,encoding="utf-8"))
    method.send(conn, state)
Пример #22
0
def buildIndex():
    #build local index
    
    #select local tree nodes
    treenodes=[(0.3,1.2),(0.2,2.4),(0.3,0.4)]
    #build global index
    for i in range(len(treenodes)):
       if treenodes[i][0]-1.0<0.0001:
          command='pub+'+str(pir['1']) + '+'+str(HOST)+'+'+str(treenodes[i])
          method.send(pir['1'],1111,command)
       if treenodes[i][1]>1.0:
          command='pub+'+str(pir['2']) + '+'+str(HOST)+'+'+str(treenodes[i])
          method.send(pir['2'],1111,command)
       if treenodes[i][1]>2.0:
          command='pub+'+str(pir['3']) + '+'+str(HOST)+'+'+str(treenodes[i])
          method.send(pir['3'],1111,command)
Пример #23
0
def recv_file(sock, sender, loc, file_name):
    Msg = "{0}{1}\r\n{2}\r\n{3}".format(DOWNFILE, sender, loc, file_name)
    method.send(sock, Msg)
    print("request:", file_name)