是否可以使用套接字.IO服务器与纯html5 websockets



我想在我的web应用程序中使用socket.我不想使用socket。Io 库在客户端。但是对于服务器端来说是可以的。我可以这样做吗?

现在使用套接字。io在服务器和纯websocket在客户端,我有销毁非套接字。io upgrade错误。我搜索了一下,这意味着我必须使用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>

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

相关内容

  • 没有找到相关文章

最新更新