是否可以使用带有纯html5 websockets的socket.io服务器?

时间:2013-06-12 15:35:30

标签: websocket socket.io

我想在我的网络应用中使用套接字。我不想在客户端使用 socket.io 库。虽然服务器端没问题。我可以这样做吗?

现在服务器上的 socket.io 和客户端上的纯websocket我有销毁nonsocket.io upgrade 错误。我用Google搜索,这意味着我必须在客户端使用 socket.io-client 库。有什么办法可以避免吗?我不希望客户端对这个库很紧张,而是使用纯html5 websocket。

如果不可能,我应该使用什么服务器连接纯html5 websockets?

如果有人好奇,这是我的服务器代码(coffeescript文件)

# Require HTTP module (to start server) and Socket.IO
http = require 'http'
io = require 'socket.io'    

# Start the server at port 8080
server = http.createServer (req, res) ->
    # Send HTML headers and message
    res.writeHead 200, { 'Content-Type': 'text/html' }
    res.end "<h1>Hello from server!</h1>"

server.listen 8080

# Create a Socket.IO instance, passing it our server
socket = io.listen server

# Add a connect listener
socket.on 'connection', (client) ->

    # Create periodical which ends a message to the client every 5 seconds
    interval = setInterval ->
        client.send "This is a message from the server!  #{new Date().getTime()}"
    , 5000

    # Success!  Now listen to messages to be received
    client.on 'message', (event) ->
        console.log 'Received message from client!', event

    client.on 'disconnect', ->
        clearInterval interval
        console.log 'Server has disconnected'

这是客户端

<script>
    // Create a socket instance
    socket = new WebSocket('ws://myservername:8080');

    // Open the socket
    socket.onopen = function (event) {
        console.log('Socket opened on client side', event);

        // Listen for messages
        socket.onmessage = function (event) {
            console.log('Client received a message', event);
        };

        // Listen for socket closes
        socket.onclose = function (event) {
            console.log('Client notified socket has closed', event);
        };
    };
</script>

1 个答案:

答案 0 :(得分:0)

我找到了这个库,似乎可以满足我的需求https://npmjs.org/package/ws