Socket.io - 无法从客户端向服务器端发送消息

时间:2015-07-26 03:54:43

标签: jquery node.js sockets express socket.io

我有两个文件 -

  • 的index.html
  • index.js

index.html 中,我有一个文本框。我想在控制台(node.js的命令提示符)的文本框中显示键入的消息。

enter image description here

index.html 中,我写了这个 -

int main(int argc, char* argv[]) {
  SDL_Window *window;                    // Declare a pointer
  SDL_Init(SDL_INIT_VIDEO);              // Initialize SDL2

  // Create an application window with the following settings:
  window = SDL_CreateWindow(
    "An SDL2 window",                  // window title
    SDL_WINDOWPOS_UNDEFINED,           // initial x position
    SDL_WINDOWPOS_UNDEFINED,           // initial y position
    640,                               // width, in pixels
    480,                               // height, in pixels
    SDL_WINDOW_OPENGL                  // flags - see below
  );

  // Check that the window was successfully made
  if (window == NULL) {
    // In the event that the window could not be made...
    printf("Could not create window: %s\n", SDL_GetError());
    return 1;
  }

  // The window is open: enter program loop (see SDL_PollEvent)
  SDL_Delay(3000);  // Pause execution for 3000 milliseconds, for example

  // Close and destroy the window
  SDL_DestroyWindow(window);

  // Clean up
  SDL_Quit();
  return 0;
}

在服务器端,在 index.js 中我使用了这个 -

<script>
  var socket = io();
  $('form').submit(function(){
    socket.emit('chat message', $('#m').val());
    $('#m').val('');
    return false;
  });
</script>

但是,消息未显示在控制台中。我的代码出了什么问题? 如果需要,请参阅以下文件。

index.js

socket.on('chat message', function(msg){ //here is the listener to the event
    console.log('message: ' + msg);
  });

的index.html

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){
  console.log('a user connected');

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

socket.on('chat message', function(msg){ //here is the listener to the event
    console.log('message: ' + msg);
  });

});


http.listen(3000, function(){
  console.log('listening on *:3000');
});

1 个答案:

答案 0 :(得分:3)

在关闭<script>标记之前移动包含socket.io代码的html文件中的</body>块,以便仅在主体完成加载后加载脚本。