用套接字发送消息

时间:2016-02-17 19:16:09

标签: angularjs sockets

我只需要让用户向另一个用户发送私人消息。

我使用方法提供角度服务:

     onSend:function(data) {
       socket.emit('notification:save', {
       message:'fromClient'
       });
       console.log("emittted")
      },
      onReceive:function(){
        socket.on('notification:save',function(message){
          console.log("recieved notif on mesage send")
        })
        console.log("recieved")
      }

控制器:

if(Auth.isLoggedIn()){
     socket.onReceive();
  }

$scope.sendMessage  = function () {
      socket.onSend($scope.message.newMessage);
      $scope.message.newMessage = '';
    };
  1. 当我调用$scope.sendMessage函数时,它会发出事件,但永远无法收听事件,即永远不会触发onReceive
  2. 如何使其适应发送给特定客户?
  3. 我需要在前端听取并发出事件。只是一个通知,所以我不需要存储在db中。我是否仍需要在emiton的此部分中包含服务器端用于事件。

1 个答案:

答案 0 :(得分:0)

以下是使用socket.io的私人消息服务器的简单示例。这使用nodejs并在服务器端表达,客户端上的jquery和两者上的socketio。 client.html仅用于演示。在angular中,您将在连接到socket.io服务器之前提供用户名。在client.html中,您需要在用户名字段中输入它,然后在发送消息之前单击两个客户端上的连接。测试你可以使用2个不同的浏览器(例如,firefox为1个客户端,chrome为另一个客户端)确保每个客户端的用户名不同,否则你将向自己发送消息。

<强> server.js

<html>
<head>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<script>

    var socket;

    function connectIO() {
        socket = io.connect('http://localhost:3000/');

        socket.on('send.username', function() {
            console.log('Server requested username');
            socket.emit('reply.username', $('#username').val());
        });

        // recieve a message
        socket.on('msg.private', function(msg) {
            $('#chat').html(msg);
        });
    }

    // send the pm
    function sendPM() {
        socket.emit('msg.private', {
            to: $('#to').val(),
            message: $('#msg').val()
        });
        $('#message').val('');
    }

</script>
<form>
    <textarea id="chat" rows="10" cols="10"></textarea><br>
    Username: <input type="text" id="username"><br>
    To: <input type="text" id="to"><br>
    Message: <input type="text" id="msg"><br>
    <span onclick="sendPM()">Send</span><br>
    <span onclick="connectIO()">Connect</span>
</form>
</body>
</html>

<强> client.html

PictureBox