我需要有关Crystal Lang Websocket的帮助,我想知道如何升级Websocket上的连接。我要制作简单的Websocket服务器
答案 0 :(得分:1)
希望获得帮助
require "http/server"
SOCKETS = [] of HTTP::WebSocket
ws_handler = HTTP::WebSocketHandler.new do |socket|
puts "Socket opened"
SOCKETS << socket
socket.on_message do |message|
SOCKETS.each { |socket| socket.send "Echo back from server: #{message}" }
end
socket.on_close do
puts "Socket closed"
end
end
server = HTTP::Server.new([ws_handler])
address = server.bind_tcp "0.0.0.0", 3000
puts "Listening on http://#{address}"
server.listen
https://medium.com/@muhammadtriwibowo/simple-websocket-using-crystal-13b6f67eba61
答案 1 :(得分:-3)
如果您正在寻找可以使用的东西,则可以使用由我创建的Shivneri框架-该框架提供了JavaScript库和基于MVC的方法来创建套接字服务器。
class ChatController < Shivneri::WebSocketController
@[On("message")]
def receive_message(data : String)
# send message to caller
clients.current.emit("message", "Received message is #{data}")
# send message to all clients
clients.emit("message", "Someone sent message #{data}")
end
end
Shivneri框架提供了一个JavaScript库shivneri-ws-client-javascript,可帮助您创建实时Web应用程序
var socket = new shivneriWsClient.Instance();
socket.on("message", function(data){
console.log("data", data);
});
await socket.init(`<web-socket-url>`);
// emit event to server
socket.emit("message","Successfully connected")
它提供了许多功能,例如客户端分组,客户端连接和断开时的事件等。
有关更多信息,请查看shivneri websocket文档-https://shivneriforcrystal.com/tutorial/websocket/