장고 채팅에 해당하는 글 1

[2] 장고 채널스(django chennals) Group

Computer 비관심/Django|2017. 2. 17. 13:05
반응형

Group의 개념


urls의와 비슷한 개념의 routing.py에 이번에는 websocket.connect를 추가합니다.

websocket.receive는 소켓에 message가 전달 됬을때 발생하며

websocket.connect는 소켓에 소켓이 생성됬을 때 발생합니다. 

#routing.py

channel_routing = [
    route('websocket.receive','chat.consumers.ws_echo'),
    route('websocket.connect', 'chat.consumers.ws_add'),
]

그러면 consumers.py에서 ws_add를 만들고 그룹에 있는 사람들이 메시지를 모두 받을 수 있도록 ws_echo를 수정해 보겠습니다. 

이전 글에서도 말했듣이 consumers.py는 장고의 views.py와 비슷하다고 볼 수 있습니다.  


ws_add에서는 routing.py에 websocket.connect가 실행되면 Group('chat')이라는 객체를 만든뒤 웹소켓 연결을 통해 만들어진 인스턴스들을 추가합니다.


ws_echo도 Goup('chat').send({text:브라우저로 보낼내용})

# consumers.py

from channels import Group


def ws_add(message):
    Group('chat').add(message.reply_channel)


def ws_echo(message):
    Group('chat').send({
        'text': message.content['text'],
    })


소캣객체 생성부터 메시지보내기 까지 3번 반복~

for (var i = 0; i < 3; ++i) {
  // Create a new WebSocket
  var ws = new WebSocket((window.location.protocol == 'http:' ? 'ws://' : 'wss://') +  window.location.host + '/')
  // Assign it an id
  ws.id = i;
  // Make it show a console message when a message is received
  ws.onmessage = function(message) {
    console.log('W' + this.id + ': ' + message.data);
  }
  // Send a new message when the WebSocket opens
  ws.onopen = function() {
    this.send('Hello, world');
  }
}

소켓을 만들고 ws.onmessage 즉 메시지가 왔으면 console.log를 사용해 message.data의 내용을 console에 뿌려준다.

ws.send는 서버에 내용을 hellow,world를 전달해준다.

반응형

댓글()