我有2个用户互相聊天。现在我想要使用这些字段"id", "content","user1","user2"
同时插入2个用户名。
Html
<div class="message-wrap col-lg-8">
<div class="msg-wrap">
<div class="media msg " id="messages">
</div>
</div>
<div class="send-wrap ">
<textarea class="form-control send-message" rows="3" placeholder="Write a reply..." id="messageInput"></textarea>
</div>
<form class="form-inline" id="messageForm">
{!! csrf_field() !!}
<div>
<input type="submit" value="Gửi" id="sendMess" class="btn btn-primary btn-block" />
</div>
</form>
</div>
服务器端:
//require module
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
//crate instance of express and http
var app = express();
var server = http.createServer( app );
//listen to socket from server
var io = socket.listen( server );
//when client connect to server console.log
io.sockets.on( 'connection', function( client ) {
console.log( "New client !" );
//when we receive message
client.on( 'message', function( data ) {
console.log( 'Message received ' + data.name + ":" + data.message +' avatar' +data.avatar );
io.sockets.emit( 'message', { name: data.name, message: data.message,avatar:data.avatar } );
});
});
server.listen( 8080 );
客户端
var socket=io.connect( 'http://localhost:8080' );
$("#messageForm").submit(function(){
var username=$("#welcome_user").text();
var msg=$("#messageInput").val();
var avatar=$("#user_avatar").attr('src');
var token=$("input[name='_token']").val();
socket.emit('message',{name:username,message:msg,avatar:avatar});
$.ajax({
url: "/saveMessage",
type: "POST",
data: { name: username, message: msg,_token:token },
success: function(data) {
console.log(data.mess);
}
});
return false;
});
socket.on('message' ,function(data){
var actualContent=$("#messages").html();
var cur_time=new Date().toTimeString().split(" ")[0];
var newContent='<span class="pull-left" href="#">'+'<img class="media-object" style="width: 32px; height: 32px;float: left;margin-right: 10px;" src='+data.avatar+'>'+'</span><div class="media-body"><h5 class="media-heading username">'+data.name+'</h5><small class="col-lg-10 message_content">'+data.message+'</small></div>';
$("#messages").append(newContent);
});
通过这样做,我只能得到1个用户。那么我怎么能用socket.io做到这一点。 谢谢你的帮助。最重要的是。