python UDP multi threaded chat room

匆匆过客 提交于 2019-12-11 15:50:17

问题


I am trying to write a python UDP chat room (that will be used later on as a room for video chats, audio calls etc). The packets arrives from the server to the client, but not from the client to the server, and I don't know why. I added prints and it is saying the packet has been sent to the ip and the port the server is listening to- so I don't know why the packets does not arrive. I will add my code, any help would be appreciated, as I really need this code to work.

Server:

__author__ = 'user'

import socket
import time
import json
import sys
import threading

class User():
    def __init__(self, IP, Port, username):
        self.IP = IP
        self.Port = Port
        self.username = username


class HandleClient(threading.Thread):
    def __init__(self, user, sock):
        threading.Thread.__init__(self)
        self.user = user
        self.sock = sock
        print "ip" + str(sock.getsockname()[0])
        print "port" + str(sock.getsockname()[1])
        message = self.user.username + " has joined the room"
        self.broadcast(message)

def run(self):
    while True:
        print "here"
        print "ip" + str(self.sock.getsockname()[0])
        print "port" + str(self.sock.getsockname()[1])
        data, addr = self.sock.recvfrom(1024)
        print "not here"
        json.loads(data)
        print "received" + data
        if data:
            if data == "QUIT":
                message = self.user.username + " has left the room"
                self.broadcast(message)
                break
            message = self.user.username + ": " + json.loads(data)
            self.broadcast(json.dumps(message))

def broadcast(self, data):
    for user in USERS:
        final_data = json.dumps(data)
        final_ip = user.IP
        final_port = user.Port + 1
        self.sock.sendto(final_data, (final_ip, final_port))
        print "sent " + final_data + "to: " + final_ip +" "+str(final_port)

IP = sys.argv[1]
Port = int(sys.argv[2])

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind((IP, Port))
server_socket.settimeout(None)

print "Server up"

USERS = []
THREADS = []

cnt = 1
dont = False

while True:
    time.sleep(0.01)
    dont = False
    try:
        data, addr = server_socket.recvfrom(1024)
    print addr[0], addr[1]
    json.loads(data)
    data = data[1 : len(data) - 1]
    splitted = data.split('~')
    if splitted[0] == "HELLO":
        new_user = User(addr[0], addr[1], splitted[1])
        for user in USERS:
            if user == new_user:
                dont = True
                break

        if not dont:
            USERS.append(new_user)
            print str(new_user.username) + " has connected"
            temp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            temp_sock.bind((IP, Port + cnt))
            temp_sock.settimeout(None)
            cnt += 1

            new_thread = HandleClient(new_user, temp_sock)
            new_thread.start()
            THREADS.append(new_thread)


    else:
        pass
except:
    pass

server_socket.close()

for t in THREADS:
    t.join

client:

__author__ = 'user'

import socket
import time
import json
import sys
import threading

class HandleSending(threading.Thread):
    def __init__(self, sock):
        threading.Thread.__init__(self)
        self.sock = sock
        message = "HELLO" + "~" + username
        self.sock.sendto(json.dumps(message), (IP, Port))
        print "sent " + message + "to: " + IP + " " + str(Port)

    def run(self):
        while True:
            try:
                data = raw_input()
                if data == "QUIT":
                    self.sendto(json.dumps(data), (IP, Port + addition))
                    print "sent " + data + "to: " + IP + " " + str(Port)
                    break
                final_data = json.dumps(data)
                final_ip = IP
                final_port = Port + addition
                self.sock.sendto(final_data, (final_ip, final_port))
                print "sent " + final_data + "to: " + final_ip + " " + str(final_port)
            except:
                pass

class HandleRecieving(threading.Thread):
    def __init__(self, sock):
        threading.Thread.__init__(self)
        self.sock = sock

    def run(self):
        while True:
            print "no"
            print "ip" + str(self.sock.getsockname()[0])
            print "port" + str(self.sock.getsockname()[1])
            try:
                data, addr = self.sock.recvfrom(1024)
                print "received " + data
                if data:
                    json.dumps(data)
                    print data
            except:
                pass

done = False

IP = sys.argv[1]
Port = int(sys.argv[2])
username = sys.argv[3]
addition = int(sys.argv[4])

client_sending_sock_ip = IP
client_sending_sock_port = Port + 1
client_sending_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_sending_sock.bind((client_sending_sock_ip, client_sending_sock_port))
client_sending_sock.settimeout(None)
client_sending_thread = HandleSending(client_sending_sock)
client_sending_thread.start()

client_recieving_sock_ip = IP
client_recieving_sock_port = Port + 2
client_recieving_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_recieving_sock.bind((client_recieving_sock_ip, 
client_recieving_sock_port))
client_recieving_sock.settimeout(None)
client_recieving_thread = HandleRecieving(client_recieving_sock)
client_recieving_thread.start()

while True:
    time.sleep(0.1)
    if done:
        client_sending_thread.join
        client_recieving_thread.join

来源:https://stackoverflow.com/questions/48856622/python-udp-multi-threaded-chat-room

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!