로르베르
58
2018-06-13 16:46:33
0
151

파이썬 Chatserver 수정좀 도움부탁드립니다.


#!/usr/bin/python3

import socket

import threading

import select


host='203.250.133.88'

port=19787

BUFSIZ = 1024

connections = {}

#{client_sock: name} key=client_sock value=name item=key:value


def init_chat(sock):

    try:

        name = sock.recv(BUFSIZ).decode()

        welcome = "Welcome {}. if want to quit, send me 'Bye!'".format(name)

        sock.send(welcome.encode())

        message = "{} has joined...".format(name)

        broadcast(message.encode())

        connections[sock] = name

        relay_message(sock, name)

    except:

        pass

    return



def relay_message(sockfd, sender_name):

    while True:

        try:

            message = sockfd.recv(BUFSIZ)

        except ConnectionResetError:

            break


        if message.decode() != "Bye!":

            broadcast(message, sender_name)

        else:

            sockfd.close()

            del connections[sockfd]

            broadcast("{} has left...".format(sender_name).encode())

            break

    return



def broadcast(msg, nickname=""):

    #Broadcasts a message to all the clients.

    if not nickname:

        nickname = "Server"

    #dictionary dict.keys(), dict.values(), dict.items(): default is keys()

    for sock in connections:

        message = nickname + ': ' + msg.decode()

        sock.sendall(message.encode())

    return


conn_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

conn_sock.bind((host, port))

conn_sock.listen(5)


while True:

     print("Waiting for connection...")

     data_sock, client_addr = conn_sock.accept()

     print("Client from {} has connected...".format(client_addr[0]))

     data_sock.send("Hi there, Please send me your nickname@@".encode() )


     client_thread = threading.Thread(target=init_chat, args=(data_sock,))

     client_thread.setDaemon(True)

     client_thread.start()


위 소스는 쓰레딩으로 구현한것인데

select 나 epoll로 구현할경우 어떻게 수정해야할지 모르겟습니다

조언좀부탁드립니다!

0
0
  • 답변 0

  • 로그인을 하시면 답변을 등록할 수 있습니다.