Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backend] game 소켓 생성 #165

Merged
merged 1 commit into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/backend/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.core.asgi import get_asgi_application

from chat.middleware import JWTAuthMiddlewareStack
from chat.routing import websocket_urlpatterns
from backend.routing import websocket_urlpatterns

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")
django_asgi_app = get_asgi_application()
Expand Down
9 changes: 9 additions & 0 deletions backend/backend/routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.urls import re_path

from chat.consumers import ChatConsumer as ChatConsumer
from game.consumers import GameConsumer as GameConsumer

websocket_urlpatterns = [
re_path(r"ws/chat/$", ChatConsumer.as_asgi()),
re_path(r"ws/game/$", GameConsumer.as_asgi()),
]
1 change: 1 addition & 0 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
'chat',
'block',
'friend',
'game',
]

MIDDLEWARE = [
Expand Down
9 changes: 5 additions & 4 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
path('docs/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path("chat/", include("chat.urls")),
path("game/", include("game.urls")),

# user
path('api/users/<int:pk>/profile-image/', UserProfileUpdateView.as_view(), name='userprofile-update'),
Expand All @@ -65,10 +66,10 @@
path('api/users/<int:user_id>/friends/<int:friend_id>/', FriendDeleteView.as_view(), name='user-friend-delete'),
path('api/friends/', FriendListView.as_view(), name='user-friend-list'),

# chat
path("api/socket/chat/single_message/", SingleMessage.as_view(), name="total"),
path("api/socket/chat/total_message/", TotalMessage.as_view(), name="total"),
path("api/socket/chat/login_message/", LoginMessage.as_view(), name="total"),
# game
path("api/socket/game/single_message/", SingleMessage.as_view(), name="total"),
path("api/socket/game/total_message/", TotalMessage.as_view(), name="total"),
path("api/socket/game/login_message/", LoginMessage.as_view(), name="total"),

]

Expand Down
7 changes: 0 additions & 7 deletions backend/chat/routing.py

This file was deleted.

Empty file added backend/chat/service.py
Empty file.
4 changes: 2 additions & 2 deletions backend/chat/templates/chat/index.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!-- chat/templates/chat/index.html -->
<!-- game/templates/game/index.html -->
<!DOCTYPE html>
<html>
<head>
Expand All @@ -21,7 +21,7 @@
document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/chat/' + roomName + '/';
{#window.location.pathname = '/chat/every';#}
{#window.location.pathname = '/game/every';#}
};
</script>
</body>
Expand Down
4 changes: 2 additions & 2 deletions backend/chat/templates/chat/room.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!-- chat/templates/chat/room.html -->
<!-- game/templates/game/room.html -->
<!DOCTYPE html>
<html>
<head>
Expand All @@ -16,7 +16,7 @@
{#const chatSocket = new WebSocket(#}
{# 'ws://'#}
{# + window.location.host#}
{# + '/ws/chat/'#}
{# + '/ws/game/'#}
{# + roomName#}
{# + '/'#}
{#);#}
Expand Down
2 changes: 1 addition & 1 deletion backend/chat/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# chat/urls.py
# game/urls.py
from django.urls import path

from . import views
Expand Down
10 changes: 5 additions & 5 deletions backend/chat/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def room(request, room_name):

class TotalMessage(APIView):
@swagger_auto_schema(
operation_description="ws://localhost:8000/ws/chat/ \n"
operation_description="ws://localhost:8000/ws/game/ \n"
"전체 채팅 메시지 수신",
responses={
200: openapi.Response('수신할 데이터', schema=openapi.Schema(
Expand All @@ -33,7 +33,7 @@ def get(self, request, *args, **kwargs):
return Response({"message": "Success"})

@swagger_auto_schema(
operation_description="ws://localhost:8000/ws/chat/ \n"
operation_description="ws://localhost:8000/ws/game/ \n"
"전체 채팅 메시지 전송",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
Expand All @@ -52,7 +52,7 @@ def post(self, request, *args, **kwargs):

class SingleMessage(APIView):
@swagger_auto_schema(
operation_description="ws://localhost:8000/ws/chat/ \n"
operation_description="ws://localhost:8000/ws/game/ \n"
"개인 채팅 메시지 수신",
responses={
200: openapi.Response('수신할 데이터', schema=openapi.Schema(
Expand All @@ -70,7 +70,7 @@ def get(self, request, *args, **kwargs):
return Response({"message": "Success"})

@swagger_auto_schema(
operation_description="ws://localhost:8000/ws/chat/ \n"
operation_description="ws://localhost:8000/ws/game/ \n"
"개인 채팅 메시지 전송",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
Expand All @@ -90,7 +90,7 @@ def post(self, request, *args, **kwargs):

class LoginMessage(APIView):
@swagger_auto_schema(
operation_description="ws://localhost:8000/ws/chat/ \n"
operation_description="ws://localhost:8000/ws/game/ \n"
"친구의 온라인 상태 메시지 수신.",
responses={
200: openapi.Response(
Expand Down
Empty file added backend/game/__init__.py
Empty file.
35 changes: 35 additions & 0 deletions backend/game/consumers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import json

import aioredis
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import AnonymousUser

from backend import settings
from game.message_type import GameMessageType


class GameConsumer(AsyncWebsocketConsumer):
REDIS_HOST, REDIS_PORT = settings.CHANNEL_LAYERS["default"]["CONFIG"]["hosts"][0]

async def redis_connection(self):
self.redis = await aioredis.from_url(f"redis://{self.REDIS_HOST}:{self.REDIS_PORT}", encoding="utf-8",
decode_responses=True)

async def connect(self):
if isinstance(self.scope['user'], AnonymousUser):
await self.close(code=4001)
else:
await self.channel_layer.group_add(GameMessageType.LOGIN_GROUP, self.channel_name)
await self.channel_layer.group_add(str(self.scope['user'].id), self.channel_name)
await self.accept()
await self.redis_connection()

async def disconnect(self, close_code):
await self.channel_layer.group_discard(GameMessageType.LOGIN_GROUP, self.channel_name)
await self.channel_layer.group_discard(str(self.scope['user'].id), self.channel_name)
self.redis.close()

async def receive(self, text_data):
text_data_json = json.loads(text_data)
message_type = text_data_json.get('type')

2 changes: 2 additions & 0 deletions backend/game/message_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class GameMessageType:
LOGIN_GROUP = "login_group"
Empty file added backend/game/service.py
Empty file.
28 changes: 28 additions & 0 deletions backend/game/templates/game/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!-- game/templates/game/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Rooms</title>
</head>
<body>
What chat room would you like to enter?<br>
<input id="room-name-input" type="text" size="100"><br>
<input id="room-name-submit" type="button" value="Enter">

<script>
document.querySelector('#room-name-input').focus();
document.querySelector('#room-name-input').onkeyup = function(e) {
if (e.key === 'Enter') { // enter, return
document.querySelector('#room-name-submit').click();
}
};

document.querySelector('#room-name-submit').onclick = function(e) {
var roomName = document.querySelector('#room-name-input').value;
window.location.pathname = '/game/' + roomName + '/';
{#window.location.pathname = '/game/every';#}
};
</script>
</body>
</html>
58 changes: 58 additions & 0 deletions backend/game/templates/game/room.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<!-- game/templates/game/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Game Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ room_name|json_script:"room-name" }}
<script>
const roomName = JSON.parse(document.getElementById('room-name').textContent);

const gameSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/game/'
);

gameSocket.onmessage = function (e) {
const data = JSON.parse(e.data);
if (data.type === 'total_message') {
const formattedMessage = `*${data.type}* [${data.datetime}] ${data.sender_nickname} ${data.sender_id}: ${data.message}\n`;
document.querySelector('#chat-log').value += formattedMessage;
} else if (data.type === 'single_message') {
const formattedMessage = `*${data.type}* [${data.datetime}] ${data.sender_nickname} ${data.sender_id}: ${data.message}\n`;
document.querySelector('#chat-log').value += formattedMessage;
} else {
document.querySelector('#chat-log').value += (data.message + '\n');
}
};

gameSocket.onclose = function (e) {
console.error('Chat socket closed unexpectedly');
};

document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function (e) {
if (e.key === 'Enter') { // enter, return
document.querySelector('#chat-message-submit').click();
}
};

document.querySelector('#chat-message-submit').onclick = function (e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
gameSocket.send(JSON.stringify({
'type': 'single_message',
'message': message,
'receiver_id': 1
}));
messageInputDom.value = '';
};
</script>
</body>
</html>
10 changes: 10 additions & 0 deletions backend/game/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# game/urls.py
from django.urls import path

from . import views


urlpatterns = [
path("", views.index, name="index"),
path("<str:room_name>/", views.room, name="room"),
]
9 changes: 9 additions & 0 deletions backend/game/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.shortcuts import render


def index(request):
return render(request, "game/index.html")


def room(request, room_name):
return render(request, "game/room.html", {"room_name": room_name})