我想在我的Web应用程序中使用套接字。但我不想在客户端使用socket.io库。尽管在服务器端使用是可以的。这可行吗?
现在,当服务器上使用socket.io而客户端使用纯websocket时,我遇到了“destroying non-socket.io upgrade”错误。我查过Google,发现这意味着我必须在客户端使用socket.io-client库。有没有办法避免这个问题?我不想让客户端与这个库绑定,而是使用纯html5 websocket。
如果不可能,那么我应该使用什么来连接纯html5 websocket的服务器?
如果有人感兴趣,这里是我的服务器代码(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>