서버가 1대가 돌아가고
클라이언트 여러대가 접속해서 그룹채팅을 이어나갈 수 있도록 만들어 봅시다.
해당 코드는 여기에
https://github.com/hyeonukdev/Python-Socket/tree/master/many
해당 개념은 여기에
https://hyeonukdev.tistory.com/110
server.py
import socket, threading
host = '127.0.0.1'
port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
nicknames = []
# 서버가 받은 메시지를 클라이언트 전체에 보내기
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
# 클라이언트로부터 타당한 메시지를 받았는지 확인
message = client.recv(1024)
# 브로드캐스트 함수 동작
broadcast(message)
except:
# 클라이언트가 나갔으면 알림
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast("{} left!\n".format(nickname).encode('ascii'))
broadcast("{} people in this room!\n".format(len(nicknames)).encode('ascii'))
nicknames.remove(nickname)
break
# 멀티 클라이언트를 받는 메서드
def receive():
while True:
client, address = server.accept()
print("Connected with {}".format(str(address)))
client.send('NICKNAME'.encode('ascii'))
nickname = client.recv(1024).decode('ascii')
nicknames.append(nickname)
clients.append(client)
print("Nickname is {}".format(nickname))
broadcast("{} joined!\n".format(nickname).encode('ascii'))
broadcast("{} people in this room!\n".format(len(nicknames)).encode('ascii'))
client.send('Connected to server!'.encode('ascii'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
client.py
import socket, threading
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 9999))
nickname = input("Choose your nickname: ")
def receive():
while True:
try:
message = client.recv(1024).decode('ascii')
if message == 'NICKNAME':
client.send(nickname.encode('ascii'))
else:
print(message)
except:
print("An error occured!")
client.close()
break
def write():
while True:
message = '{}: {}'.format(nickname, input(''))
client.send(message.encode('ascii'))
# 멀티 클라이언트용 쓰레드
receive_thread = threading.Thread(target=receive)
receive_thread.start()
# 메시지 보내기
write_thread = threading.Thread(target=write)
write_thread.start()
server를 실행하고 client를 두개 실행한 결과 입니다.
server의 broadcast 메서드를 통해서 서로가 친 채팅을 볼 수 있습니다.
반응형
'SW ENGINEERING > Programing' 카테고리의 다른 글
URL 규칙, RESTFul한 URL (0) | 2021.07.04 |
---|---|
Python Socket : 멀티쓰레드를 활용한 채팅 (0) | 2021.06.28 |
Python Socket : 1대1 채팅 (0) | 2021.06.28 |
Python Socket (0) | 2021.06.21 |
RESTful API (0) | 2021.05.31 |
최근댓글