$ django-admin startproject chatapp
$ cd chatapp
$ python manage.py startapp chat
$ pip install django-socketio
python
INSTALLED_APPS = [
...
'socketio',
'chat',
]
python
from django.conf.urls import url
from chat import views
urlpatterns = [
...
url(r'websocket/', views.websocket),
]
python
from socketio.views import enter_namespace
from chat import sockets
def websocket(request):
return enter_namespace(request, sockets)
python
from socketio.namespace import BaseNamespace
class ChatNamespace(BaseNamespace):
def on_chat_message(self, msg):
self.emit('chat_message', msg, broadcast=True)
sockets = {'/chat': ChatNamespace}
$ npx create-react-app react-app
$ cd react-app
$ npm install socket.io-client --save
jsx
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:8000/chat');
function App() {
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
socket.on('chat_message', (msg) => {
setMessages([...messages, msg]);
});
return () => {
socket.off('chat_message');
};
}, [messages]);
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
const handleSendMessage = () => {
socket.emit('chat_message', inputValue);
setInputValue('');
};
return (
<div>
<ul>
{messages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
<input type="text" value={inputValue} onChange={handleInputChange} />
<button onClick={handleSendMessage}>Send</button>
</div>
);
}
export default App;
$ python manage.py runserver
$ npm start