3

I want to use sockets in my web app. I don't want to use socket.io library on client-side. It's OK for server-side though. Can I do this?

Now with socket.io on server and pure websocket on client I have destroying non-socket.io upgrade error. I've googled that it means that I have to use socket.io-client library on client-side. Is there any way to avoid that? I don't want client to be tight with this library and use pure html5 websocket instead.

If it's not possible what should I use for server to connect with pure html5 websockets?

If someone is curious here is my server code (coffeescript file)

# 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'

And here is a client-side

<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>
4

1 回答 1

0

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

于 2013-07-11T15:20:47.680 回答