Visualizzazione dei risultati da 1 a 7 su 7
  1. #1

    Messaggi broadcast usando Socket.io

    null
    Ultima modifica di Rampant Glider; 30-05-2017 a 16:31

  2. #2
    Buongiorno a tutti, è il primo post che scrivo, volevo chiedervi questo: sto scrivendo in javascript una chat da utilizzare in rete LAN. La parte di messaggistica funziona e riesco anche a visualizzare l'IP privato quando ci si connette al server, però lo mostra solo al client. Vorrei fare in modo che venisse mostrato a tutti coloro che sono presenti nella chat, e inoltre vorrei aggiungere davanti ad ogni messaggio l'header "[] " corrispondente all'IP del mittente. Allego il codice, diviso in due file:

    File index.html:

    <!doctype html>
    <html>
    <head>
    <title>Anonymous Chat by Maxi</title>
    <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font: 13px Helvetica, Arial; }
    form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
    form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
    form button { width: 9%; background: rgb(130, 224, 255); border: none;
    padding: 10px; }
    #messages { list-style-type: none; margin: 0; padding: 0; }
    #messages li { padding: 5px 10px; }
    #messages li:nth-child(odd) { background: #eee; }
    </style>
    </head>
    <body>
    <ul id="messages"></ul>
    <form action="">
    <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="Main.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
    $(function () {
    var socket = io();
    $('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
    });
    socket.on('chat message', function(msg){
    $('#messages').append($('<li>').text(msg));
    });
    });
    </script>
    <script>
    var socket = io();
    </script>
    <script>
    //get the IP addresses associated with an account
    function getIPs(callback){
    var ip_dups = {};

    //compatibility for firefox and chrome
    var RTCPeerConnection = window.RTCPeerConnection
    || window.mozRTCPeerConnection
    || window.webkitRTCPeerConnection;
    var useWebKit = !!window.webkitRTCPeerConnection;

    //bypass naive webrtc blocking using an iframe
    if(!RTCPeerConnection){
    var win = iframe.contentWindow;
    RTCPeerConnection = win.RTCPeerConnection
    || win.mozRTCPeerConnection
    || win.webkitRTCPeerConnection;
    useWebKit = !!win.webkitRTCPeerConnection;
    }

    //minimal requirements for data connection
    var mediaConstraints = {
    optional: [{RtpDataChannels: true}]
    };

    var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};

    //construct a new RTCPeerConnection
    var pc = new RTCPeerConnection(servers, mediaConstraints);

    function handleCandidate(candidate){
    //match just the IP address
    var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
    var ip_addr = ip_regex.exec(candidate)[1];

    //remove duplicates
    if(ip_dups[ip_addr] === undefined)
    callback(ip_addr);

    ip_dups[ip_addr] = true;
    }

    //listen for candidate events
    pc.onicecandidate = function(ice){

    //skip non-candidate events
    if(ice.candidate)
    handleCandidate(ice.candidate.candidate);
    };

    //create a bogus data channel
    pc.createDataChannel("");

    //create an offer sdp
    pc.createOffer(function(result){

    //trigger the stun server request
    pc.setLocalDescription(result, function(){}, function(){});

    }, function(){});

    //wait for a while to let everything done
    setTimeout(function(){
    //read candidate info from local description
    var lines = pc.localDescription.sdp.split('\n');

    lines.forEach(function(line){
    if(line.indexOf('a=candidate:') === 0)
    handleCandidate(line);
    });
    }, 1000);
    }
    getIPs(function(ip){
    var li = document.createElement("li");
    li.textContent = "you logged in with the ip: " + ip;
    if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/))
    document.getElementsByTagName("ul")[0].appendChild(li);
    console.log(li.textContent);
    var socket = io();
    socket.emit('chat message', $('#m').val());
    });
    </script>
    </script>
    </body>
    </html>

    ---

    File index.js:
    function multiply(num1,num2) {
    var result = num1 * num2; return result;
    }
    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
    });
    io.on('connection', function(socket){
    socket.on('chat message', function(msg){
    io.emit('chat message', msg);
    });
    });
    http.listen(3000, function(){
    console.log('listening on *:3000');
    });

    ---

    P.S.: vi prego aiutatemi non so più dove sbattere la testa :(

  3. #3
    ciao!

    non sono ferratissimo con socket.io, ma penso tu debba specificarlo dentro alla funzione emit.
    una cosa del genere:
    codice:
    io.sockets.emit('broadcast',.....);
    https://www.tutorialspoint.com/socke...oadcasting.htm

    PS: metti il codice tra i tag CODE, così formatti meglio il codice, ed è più leggibile.

  4. #4
    Grazie mille! Ho risolto tutto, c'è un modo per darti un +1, o un like, o qualsiasi altra cosa?

  5. #5
    Quote Originariamente inviata da Rampant Glider Visualizza il messaggio
    Grazie mille! Ho risolto tutto, c'è un modo per darti un +1, o un like, o qualsiasi altra cosa?
    ottimo!
    like in che senso???

  6. #6
    Una valutazione positiva

  7. #7
    Quote Originariamente inviata da Rampant Glider Visualizza il messaggio
    Una valutazione positiva
    mi sa che qui non c'è il concetto di valutazione.
    cmq grazie!!

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.