Advertisement
virbo

nodechat

Apr 6th, 2020
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //file server.js
  2. //-----
  3. var app = require('express')();
  4. var http = require('http').Server(app);
  5. var io = require('socket.io')(http);
  6.  
  7. app.get('/', function (req, res) {
  8.     res.send("<h1>It works!</h1>");
  9. });
  10.  
  11. io.on('connection', function(socket){
  12.     console.log('new client connected');
  13.     socket.on('disconnet', function(){
  14.         console.log('a client disconnect');
  15.     })
  16.     socket.on('notif',function(msg){
  17.         console.log('message: '+msg.name+ ': ' + msg.message);
  18.         io.emit('notif', {name: msg.name, message: msg.message});
  19.     })
  20. });
  21.  
  22. http.listen(3000, function(){
  23.   console.log('listening on *:3000');
  24. });
  25.  
  26. //file notif.js
  27. //file ini saya load di view => $this->registerJs($this->render('notif.js'), \yii\web\View::POS_READY);
  28. var socket = io.connect('https://chatserver.dutainformasi.net');
  29. socket.on('notif', function (data) {
  30.     $( "#notifikasi" ).prepend( "<p><strong>" + data.name + "</strong>: " + data.message + "</p>" );
  31.     $.notify({
  32.         message: "<strong>" + data.name + "</strong>: " + data.message,
  33.        
  34.     }, {
  35.         type: 'success',
  36.         placement: {
  37.             from: "bottom",
  38.             align: "left"
  39.         },
  40.     })
  41. });
  42.  
  43. $('#chat-form').submit(function() {
  44.     var nama = $("#nick_name").val();
  45.     var msg = $("#message-field").val();
  46.     if ((nama != '') && (msg != '')){
  47.         socket.emit('notif',{ name: nama, message: msg});
  48.         $("#message-field").val("");
  49.     }
  50.     return false;
  51. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement