0

Hi, I have just started learning nodejs. And i am using socket.io modules. I have write code where one user can send message to another specific user.. but my code is not working, idk why ?
Here is my client side script -->

var mysql = require("mysql");
var fs = require('fs');
var httpe = require('http');
var io = require('socket.io').listen(httpe);
// First you need to create a connection to the db
var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database:"msg"
});

//connect  connection
con.connect(function(err){
  if(err){
    console.log(err);
    con.end;
    return;
  }else
  console.log('Connection established');
});
httpe.createServer(function (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
    res.writeHead(200);
    res.end(data);
  /* res.writeHead(200, {'content-type':'text/html'});
    res.write("hi there! Test Test");
    res.end(data);*/
  });
}).listen(3000);

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

  socket.on('add-user', function(data){
    clients[data.username] = {
      "socket": socket.id
    };
    console.log(clients[data.username]);
  });

  socket.on('private-message', function(data){
    console.log("Sending: " + data.content + " to " + data.username);
    if (clients[data.username]){
      io.sockets.connected[clients[data.username].socket].emit("add-message", data);
    } else {
      console.log("User does not exist: " + data.username); 
    }
  });

  //Removing the socket on disconnect
  socket.on('disconnect', function() {
    for(var name in clients) {
        if(clients[name].socket === socket.id) {
            delete clients[name];
            break;
        }
    }   
  })

});

Hree is cliente side script-->

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Socket.io Demo</title>

  <style>
    .chat-form { display: none; }
  </style>

</head>
<body>

<form class="username-form" method="post" action="">
  <input type="text" />
  <input type="submit" value="Join" />
</form>

<form class="chat-form" method="post" action="">
  <div>Hey there, <span id="username">Guest</span></div>
  <label>To:</label> <input id="recipient" /><br />
  <label>Message: </label><br />
  <textarea id="message"></textarea>
  <input type="submit" value="Send" />

  <ul id="messages">

  </ul>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

<script>
  var socket = io.connect('http://localhost');
  // Add a username
  $(".username-form").on("submit", function(){
    // Tell the server about it
    var username = $(this).children("input").val();
    socket.emit("add-user", {"username": username});
    // Remove this form and show the chat form
    $(this).remove();
    $("#username").text(username);
    chat_form.show();
    return false;
  });
  // Chat form
 var chat_form = $(".chat-form");
 chat_form.on("submit", function(){
   // Send the message to the server
   socket.emit("private-message", {
    "username": $(this).find("input:first").val(),
    "content": $(this).find("textarea").val()
   });
   // Empty the form
   $(this).find("input:first, textarea").val('');
  return false;
 });
 // Whenever we receieve a message, append it to the <ul>
 socket.on("add-message", function(data){
  $("#messages").append($("<li>", {
    "text": data.content
  }));
 });
</script>
</body>
</html>
2
Contributors
3
Replies
10
Views
2 Years
Discussion Span
Last Post by Taywin
0

At line 4, it seems to be a syntax error already. Please take a look at here. You need to specify a server or port for the listening before you set its listening port.

0

when i run in cmd my serverside code that doent give me any error neither in chrome console i see any errors ?

var httpe = require('http');
var io = require('socket.io').listen(httpe);

i have done like this httpe.createServer(function(){ // above in code }).listen(3000);
i have write port.

0

Please specify "Not working." What is it? Also, have you inspected the io variable if it is created?

Edited by Taywin

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.