通过websocket发送消息 [英] get past messages from websocket

查看:103
本文介绍了通过websocket发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有这个代码

 < script type =text / javascript> 
var ws;
var userName =;
var displayOnTextArea = function(msg){
var tarea = $('#textarea');
tarea.prepend('< div style =background:rgb(51,51,51); color:white; padding:31px; border:1px solid rgba(0,0,0,0.44); border -radius:10px; padding-top:40px; padding-bottom:20px;>'+ msg +'< / div>< br>');

$ b $ var sendMessage = function(msg){
if(userName ==SYSTEM)
ws.send(< div style ='background :rgb(88,86,86); background:-webkit-repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px);背景:重复线性渐变(45deg,#) 606dbc,#606dbc 10px,#465298 10px,#465298 20px); border:1px solid rgba(0,0,0,0.44); color:white; width:100px; text-align:center; margin-left:751px; ; margin-top:-55px; padding:5px; border-radius:10px; font-family:josefin_sansbold;'>+ userName +< / div>+ msg);
else
ws.send(< div style ='background:rgb(88,86,86);< ;? if(User :: isAdmin()){echo'background:-webkit (45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px);背景:重复线性渐变(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px) ;';}?> border:1px solid rgba(0,0,0,0.44); color:white; width:100px; text-align:center; margin-left:751px ;; margin-top:-55px; padding:5px; border-radius:10px; font-family:josefin_sansbold;'>+ userName +< / div>+ msg);
}

var safe_tags = function(str){
return str.replace(/& / g,'& amp;')。replace(/< g,'& lt;')。replace(/> / g,'& gt;');

$ b $(document).keypress(function(event){
if(event.which == 13){
if($('#input_ ').val()!=){
if($('#input _')。val()!=){
displayOnTextArea(< div style ='background: rgb(88,86,86);< ;? if(User :: isAdmin()){echo'background:-webkit-repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px); background:repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px);';}?> border:1px solid rgba(0,0,0,0.44); color:white; width:100px; text-align:center; margin-left:751px ;; margin-top:-55px; padding:5px; border-radius:10px; font-family:josefin_sansbold;'>< ;? ($('#input _')。val()));
sendMessage(safe_tags($('#input _').val)= $ User->用户名?>< / div>+ safe_tags ()));
$('#input_')。val();
}
}
}
});

$(document).ready(function(){
userName =< ;? echo $ User-> username;?>;
console.log 尝试连接到服务器);
ws = new WebSocket(ws://scribblehost.ws:1035 / avatarrealms162882); //我们需要一个serverip
ws.onopen = function ){
console.log(Connected);
userName =SYSTEM;
displayOnTextArea(< div style ='background:rgb(88,86,86); background :-webkit-repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px); background:repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#: 465298 20px); border:1px solid rgba(0,0,0,0.44); color:white; width:100px; text-align:center; margin-left:751px ;; margin-top:-55px; padding:5px ; border-radius:10px; font-family:josefin_sansbold;'> SYSTEM< / div>欢迎<?= $用户 - >用户名>聊天!);
sendMessage(欢迎<?= $用户 - >用户名?>到聊天!);
userName =<? echo $ User->用户名; (evt.msg);
displayOnTextArea(evt.data);


ws.onmessage = function(evt){
console.log ;
}
});
< / script>
< input type ='text'id ='input_'style ='font-size:20px; height: 30px; width:100%;'autofocus =autofocus/>< / div>
< div id ='textarea'style ='padding-top:15px; background:none; resize:none; border:none; font-size:20px; padding-bottom:185px; max-height:389px; padding-left:145px; margin-top:-6px; overflow-y:hidden;'>< / div>

当用户聊天时,我该如何让我如此,它显示聊天中最新的5条消息?
i尝试循环,但我不知道什么/在哪里循环



基本上,我希望它显示聊天时的最新消息他们加入,所以他们知道用户在谈论什么等等。

解决方案

TL; DR:为什么不把最后5条消息保存在数组中,然后在连接时发送数组?

消息来自用户并添加到数组/列表的末尾,数组的第一个元素将从列表中弹出。



当用户连接向所有用户发送消息时表示新用户已连接的用户。此用户发送数组的内容,并按正确顺序打印。



编辑为包含代码。



这些片段来自我正在开发的基于websockets的演示系统。

App.js

  var express = require('express'); 
var app = express();
var server = require('http')。createServer(app);
var io = require('socket.io')。listen(server);
var previousMessages = [];
$ b $ server.listen(1337,function(){
use strict;
console.log(Application start!)
});

//通常的应用程序启动的东西,使用你最好的判断。
app.get('/',function(request,response){
use strict;
var index = path.join(__ dirname,public,index.html );
response.sendfile(index);
});

io.sockets.on('connection',function(socket){
use strict;

//在websocket连接上发送以前的消息。
io.sockets.emit(msgRecv,{
msg:previousMessages
});

socket.on(msgSend,function(data) {
//新消息到达,重新计算前面的消息
//用户连接时会看到的消息
if(previousMessages.length> 4){
previousMessages .split(1,1);
previousMessages.push(data.msg);
}

//发送最新消息,而不是之前的消息

io.sockets.emit(msgRecv,{
msg:data.msg
})
});
});

stuff.js

  var socket = io.connect(meh:1337); 

函数sendMessage(){
use strict;

//假设文本框/文本字段在这里...
var msg = document.getElementById(msg).value;
socket.emit(msgSend{
msg:msg
});
}

函数RecvMessage(){
use strict;
$ b socket.on(msgRecv,function(data){
console.log(data);
}
}

请根据需要使用它,但请记住,这是来自另一个项目的上下文块,我已经测试了整个项目,但不是孤立的这些片段,除非我完全看到你的代码,否则我现在无法提出更多建议。


okay i have this code

<script type="text/javascript">
    var ws;
    var userName = "";
    var displayOnTextArea = function ( msg ) {
        var tarea = $('#textarea');
        tarea.prepend (  '<div style="background: rgb(51, 51, 51); color: white; padding: 31px; border: 1px solid rgba(0, 0, 0, 0.44); border-radius: 10px; padding-top: 40px; padding-bottom: 20px;">' + msg + '</div><br>');  
    }

    var sendMessage = function ( msg ) {
        if (userName == "SYSTEM")
            ws.send ( "<div style='background: rgb(88, 86, 86); background: -webkit-repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px); background: repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px); border: 1px solid rgba(0, 0, 0, 0.44); color: white; width: 100px; text-align: center; margin-left: 751px;; margin-top: -55px; padding: 5px; border-radius: 10px; font-family: josefin_sansbold;'>" + userName + "</div> " + msg );   
        else
            ws.send ( "<div style='background: rgb(88, 86, 86); <? if(User::isAdmin()) { echo 'background: -webkit-repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px); background: repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px);'; } ?> border: 1px solid rgba(0, 0, 0, 0.44); color: white; width: 100px; text-align: center; margin-left: 751px;; margin-top: -55px; padding: 5px; border-radius: 10px; font-family: josefin_sansbold;'>" + userName + "</div> " + msg ); 
    }

    var safe_tags = function(str) {
        return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') ;
    }

    $(document).keypress ( function ( event ) {
         if ( event.which == 13 ) { 
            if ( $('#input_').val() != "" ) {
                if ( $('#input_').val() != " " ) {
                    displayOnTextArea ( "<div style='background: rgb(88, 86, 86); <? if(User::isAdmin()) { echo 'background: -webkit-repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px); background: repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px);'; } ?> border: 1px solid rgba(0, 0, 0, 0.44); color: white; width: 100px; text-align: center; margin-left: 751px;; margin-top: -55px; padding: 5px; border-radius: 10px; font-family: josefin_sansbold;'><?=$User->username?></div>" +   safe_tags($('#input_').val()));
                    sendMessage ( safe_tags($('#input_').val()) );
                    $('#input_'). val ( "" );
                 }
             }
         }
    } );

    $(document).ready ( function ( ) {
            userName = "<? echo $User->username; ?>";
            console.log ( "Attempting to connect to server" );
            ws = new WebSocket ( "ws://scribblehost.ws:1035/avatarrealms162882" ); //We need a serverip.
            ws.onopen = function ( ) {
                console.log ( "Connected" );
                userName = "SYSTEM";
                displayOnTextArea ( "<div style='background: rgb(88, 86, 86); background: -webkit-repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px); background: repeating-linear-gradient(45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px); border: 1px solid rgba(0, 0, 0, 0.44); color: white; width: 100px; text-align: center; margin-left: 751px;; margin-top: -55px; padding: 5px; border-radius: 10px; font-family: josefin_sansbold;'>SYSTEM</div> Welcome <?=$User->username?> to the chat!");
                sendMessage ( "Welcome <?=$User->username?> to the chat!" );
                userName = "<? echo $User->username; ?>";
            }

            ws.onmessage = function ( evt ) {
                console.log ( evt.msg );    
                displayOnTextArea ( evt.data );
            }
    } );
</script>
<input type='text' id='input_' style='font-size:20px;height:30px;width: 100%;' autofocus="autofocus" /></div>
<div id='textarea' style='padding-top: 15px; background: none; resize: none; border: none; font-size: 20px; padding-bottom: 185px; max-height: 389px; padding-left: 145px; margin-top: -6px; overflow-y: hidden;'></div>

How can I make i so when the user jois the chat, it shows the 5 latest messages on the chat? i tried looping but i can't figure out what/where to loop

basically, i'd like it to show the latest messages on the chat when they join so they know what the users are talking about, etc.

解决方案

TL;DR: Why not keep the last five messages in an array, then send the array upon connection?

Message comes in from a user and is added to the end of an array/list, the first element of the array is then popped off the list.

When a user connects send a message to all users that indicates a new users has connected. This user is send the contents of the array and they are printed in the correct order.

EDITED TO INCLUDE CODE.

These snippets are taken from a websockets based presentation system I'm working on.

App.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var previousMessages = [];

server.listen(1337, function() {
  "use strict";
  console.log("Application start!")
});

// Usual application start stuff, use your best judgement.
app.get('/', function(request, response) {
  "use strict";
  var index = path.join(__dirname, "public", "index.html");
  response.sendfile(index);
});

io.sockets.on('connection', function(socket) {
  "use strict";

  // On websocket connection send previous messages.
  io.sockets.emit("msgRecv", {
    "msg": previousMessages
  });

  socket.on("msgSend", function(data) {
    // New message arrived, re-calculate the previous messages
    // that users will see when they connect.
    if (previousMessages.length > 4) {
      previousMessages.split(1, 1);
      previousMessages.push(data.msg);
    }

    // Send the latest message, not the previous messages,
    // the user is already connected.
    io.sockets.emit("msgRecv", {
      "msg": data.msg 
    })
  });
});

stuff.js

var socket = io.connect("meh:1337");

function sendMessage() {
  "use strict";

  // Assuming a textbox/textfield here...
  var msg = document.getElementById("msg").value;
  socket.emit("msgSend" {
    "msg": msg
  });
}

function RecvMessage() { 
  "use strict";

  socket.on("msgRecv", function(data) {
    console.log(data);
  }
}

Please use this as you need to, but remember this is out of context chunks from another project. I've tested the project as a whole, but not these snippets in isolation, unless I saw your code in its entirety I'd be unable to suggest more at this point.

这篇关于通过websocket发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆