我想在我的web应用程序中使用套接字。我不想在客户端使用socket.io库。不过对于服务器端来说是可以的。我可以这么做吗?
现在,在服务器上使用socket.io,在客户端使用纯websocket,我已经破坏了非socket.io升级错误。我在谷歌上搜索到,这意味着我必须在客户端使用socket.io-client库。有什么办法可以避免吗?我不希望客户机使用这个库而使用纯html5 websocket。
如果它是不可能的,我应该使用什么服务器连接纯html5网络套接字?
如果有人好奇,这里是我的服务器代码(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