Este es mi server.js
Código Javascript:
Ver original
var redis = require('../node_modules/redis'); var socket = require('../node_modules/socket.io' ); var express = require('../node_modules/express'); var app = express(); var server = require('http').createServer(app); var io = socket.listen( server ); var port = process.env.PORT || 3002; let sequenceNumberByClient = new Map(); server.listen(port, function () { console.log('Server listening at port %d', port); }); io.on('connection', function (socket) { socket.on('channel', (channel) => { redisClient.subscribe(channel); }) var redisClient = redis.createClient(); sequenceNumberByClient.set(socket, 1); redisClient.on("message", function(channel, data) { socket.emit(channel, data); }); socket.on('disconnect', function() { sequenceNumberByClient.delete(socket); redisClient.quit(); }); });
mi código del cliente
Código Javascript:
Ver original
<script> var socket = io.connect('http://localhost:3002'); $('.usuarios').on('click', '.users-to', function() { $("#messages").empty (); channel = $(this).val()+''+{{ \Auth::user()->id }}; var token_messages = '{{ csrf_token() }}'; var user_to = $(this).val(); $.ajax({ type: "POST", url: '{!! URL::to("getmessages") !!}', dataType: "json", data: {'_token':token_messages, 'userTo':user_to}, success:function(data){ $.each(data.messageList, function (index, value) { class_msg = ''; if(value.user_to == {{ \Auth::user()->id }} ) { class_msg = 'replies'; }else{ class_msg = 'sent'; } $( "#messages" ).append( "<li class='"+class_msg+"'><img src='http://emilcarlsson.se/assets/mikeross.png' alt=''/><p>"+value.name+": "+value.message+"</p></li>" ); }); } }); socket.emit('channel', channel); setChannel(channel); }); function setChannel(channelValue){ socket.on(channelValue, function (data) { data = jQuery.parseJSON(data); $( "#messages" ).append( "<li class='sent'><img src='http://emilcarlsson.se/assets/mikeross.png' alt=''/><p>"+data.user+": "+data.message+"</p></li>" ); }); } $(".send-msg").click(function(e){ e.preventDefault(); var token = '{{ csrf_token() }}'; var user = $("input[name='user']").val(); var msg = $(".msg").val(); var user_to = {{ $user->id }}; if(msg != ''){ $.ajax({ type: "POST", url: '{!! URL::to("sendmessage") !!}', dataType: "json", data: {'_token':token,'message':msg,'user':user, 'userTo':user_to, 'channel': channel}, success:function(data){ console.log(data); console.log(data.user); $(".msg").val(''); } }); }else{ alert("Please Add Message."); } }) </script>
Y este mi controlador en Laravel
Código PHP:
Ver original
public function sendMessage(Request $request) { try { $redis = LRedis::connection(); $chatRepo = new ChatRepo(); $message = $request->message; $userTo = $request->userTo; $user = $user_ex[0]; $userFrom = \Auth::user()->id; $status = 1; $key = \Uuid::generate(4)->string; $read = 0; $chatMessage = $chatRepo->createChatMessage($userFrom, $userTo, $message, $status, $key, $read); $data = ['message' => $message, 'user' => $user]; $channel = $request->channel; return response()->json($data, 200); } catch (\Exception $ex) { return redirect()->back()->with('error_string', _('Ha ocurrido un error.')); } }
El error que tengo es que cuando le doy click sobre un usuario para enviarle el mensaje, si le doy click 2 o mas veces a ese usuario, o cambio de un usuario a otro, se me duplican los mensajes que envío tantas veces haga click en los botones de usuario. Espero me puedan ayudar feliz tarde.