GVKun编程网logo

PHP棘轮websocket SSL连接?

4

想了解PHP棘轮websocketSSL连接?的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于AndroidWebSocket中的SSL连接错误、c#–在.NetCore中将Nexmo

想了解PHP棘轮websocket SSL连接?的新动态吗?本文将为您提供详细的信息,此外,我们还将为您介绍关于Android WebSocket中的SSL连接错误、c# – 在.Net Core中将Nexmo连接到Websocket失败(远程方关闭了WebSocket)、Go WebSocket 如何处理并发连接?、Go WebSocket 如何处理断开连接?的新知识。

本文目录一览:

PHP棘轮websocket SSL连接?

PHP棘轮websocket SSL连接?

我有一个棘手的聊天服务器文件

use Ratchet\Server\IoServer;use Ratchet\WebSocket\WsServer;use MyAppChat\Chat;require dirname(__DIR__) . ''/vendor/autoload.php'';$server = IoServer::factory(    new WsServer(        new Chat()    )  , 26666);$server->run();

我使用Websocket进行连接,ws效果很好

if ("WebSocket" in window) {    var ws = new WebSocket("ws://ratchet.mydomain.org:8888");    ws.onopen = function() {        // Web Socket is connected. You can send data by send() method.        ws.send("message to send");    };    ws.onmessage = function (evt) {         var received_msg = evt.data;    };    ws.onclose = function() {         // websocket is closed.     };} else {  // the browser doesn''t support WebSocket.}

我想要安全连接,因此我尝试使用SSL连接,但无法正常工作。

if ("WebSocket" in window) {    var ws = new WebSocket("wss://ratchet.mydomain.org:8888");    ws.onopen = function() {        // Web Socket is connected. You can send data by send() method.        ws.send("message to send");    };    ws.onmessage = function (evt) {         var received_msg = evt.data;    };    ws.onclose = function() {         // websocket is closed.     };} else {  // the browser doesn''t support WebSocket.}

我的问题是 如何将Websocket与SSL连接连接

任何的想法?

答案1

小编典典

如果您使用的是Apache Web服务器(2.4或更高版本),请在httpd.conf文件中启用以下模块:

  1. mod_proxy.so
  2. mod_proxy_wstunnel.so

将此设置添加到您的httpd.conf文件

ProxyPass /wss2/ ws://ratchet.mydomain.org:8888/

需要WSS连接时,请在JavaSscript调用中使用以下URL:

var ws = new WebSocket("wss://ratchet.mydomain.org/wss2/NNN");

重新启动Apache Web服务器,并在应用设置(telnet主机名端口)之前,确保您的Ratchet worker(Web套接字连接)已打开。

Android WebSocket中的SSL连接错误

Android WebSocket中的SSL连接错误

我开发了一个演示android应用程序,该应用程序通过安全的websocket协议连接到在线服务器.
并且在开始连接时收到“找不到证书路径的信任锚”错误.我搜索了此错误,仅找到了相关的HTTPS,我不知道如何在websocket(wss)中进行开发.

我将Autobahn-SW库用于websocket.

代码在这里(在“我的活动”课程中):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final WebSocketConnection mConnection = new WebSocketConnection();

    final String wsuri = "wss://myserver_url";
    try {
        mConnection.connect(URI.create(wsuri), new WebSocketConnectionObserver() {

            @Override
            public void onopen() {
                System.out.println("onopend----> sending msg...");
                mConnection.sendTextMessage("hello");
            }

            @Override
            public void onClose(WebSocketCloseNotification code, String reason) {
                System.out.println("onClosed---> " + reason);
            }

            @Override
            public void onTextMessage(String payload) {
                System.out.println("onTextmessage---> " + payload);
            }

            @Override
            public void onRawTextMessage(byte[] payload) {
            }

            @Override
            public void onBinaryMessage(byte[] payload) {
            }

        });
    } catch (Exception e) {
        e.printstacktrace();
    }
}

而且我得到如下错误:

07-21 13:16:46.159: D/de.tavendo.autobahn.secure.WebSocketConnection(4023): WebSocket connection created.
07-21 13:16:46.329: 
D/de.tavendo.autobahn.secure.WebSocketReader(4023): WebSocket reader created.
07-21 13:16:46.349: 
D/de.tavendo.autobahn.secure.WebSocketConnection(4023): WebSocket reader created and started.
07-21 13:16:46.349: 
D/de.tavendo.autobahn.secure.WebSocketWriter(4023): WebSocket writer created.
07-21 13:16:46.449: 
E/de.tavendo.autobahn.secure.WebSocketReader(4023): java.security.cert.CertPathValidatorException: Trust anchor for certification path not 
found.
07-21 13:16:46.479: E/de.tavendo.autobahn.secure.WebSocketWriter(4023): Socket is closed
07-21 13:16:46.479: 
D/de.tavendo.autobahn.secure.WebSocketWriter(4023): WebSocker writer running.
07-21 13:16:46.479: 
D/de.tavendo.autobahn.secure.WebSocketConnection(4023): WebSocket writer created and started.
07-21 13:16:46.499: 
D/de.tavendo.autobahn.secure.WebSocketConnection(4023): fail connection [code = INTERNAL_ERROR, reason = WebSockets internal error 
(java.lang.NullPointerException)
07-21 13:16:46.499: D/de.tavendo.autobahn.secure.WebSocketReader(4023): quit
07-21 13:16:46.499: 
D/de.tavendo.autobahn.secure.WebSocketWriter(4023): WebSocket writer ended.
07-21 13:16:46.499: 
D/de.tavendo.autobahn.secure.WebSocketConnection(4023): SocketThread exited.

如何连接Secure Websocket(wss)?代码示例将很有帮助.

解决方法:

感谢@Jack,我解决了以下解决方案:就我而言,我的服务器生成了自我认证证书.但是在服务器获得相关的经过验证的SSL证书后,将不需要(下面)代码.

我也从HTTPS GET (SSL) with Android and self-signed server certificate得到了解决方案.

/*************************************************************************************************/
            /* Below code is only purposed for Testing, Not to use in real environment */
            /**
             * Setting custom Trust managers which are intended to allow SSL connection to server.
             * This custom trust managers are allowing for all connection types, so this may cause network connection security leak.
             * So those are used only for testing purposes.
             *              
             * Doc - http://developer.android.com/training/articles/security-ssl.html#SelfSigned
             * */
            WebSocketClient.setTrustManagers(new TrustManager[] {
              new x509trustmanager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                    public X509Certificate[] getAcceptedissuers() { return new X509Certificate[]{}; }
                  }
            });
            /*************************************************************************************************/

            wsClient = new WebSocketClient(uri, this , extraHeaders);       
            wsClient.connect();

c# – 在.Net Core中将Nexmo连接到Websocket失败(远程方关闭了WebSocket)

c# – 在.Net Core中将Nexmo连接到Websocket失败(远程方关闭了WebSocket)

我正在尝试在进行呼入时将Nexmo连接到Web套接字(用户使用nexmo调用已购买的号码并链接到应用程序).

截至目前,我只是尝试这个Sample Code(简单地回复了调用者所说的内容),并按照“文档”Here通过Nexmo连接到这个websocket.

我成功地向nexmo发送了一个动作“connect”.在调用Nexmo购买的号码时,它正确地重定向到端点(api / nexmo / socket),如使用断点时所示,但是当它在Echo方法中到达webSocket.ReceiveAsync时它会挂起.

using System;
    using System.Net.WebSockets;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json.Linq;

    namespace MyProject.Web.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class NexmoController : ControllerBase
        {
            private WebSocket _webSocket;

            [HttpGet("answer")]
            public IActionResult AnswerHandler()
            {
                const string host = "MY_NGROK_URL";
                const string locale = "fr-FR";

                var nccos = new JArray();
                var nccoConnect = new JObject()
                {
                    { "action","connect" },{ "endpoint",new JArray(new JObject{
                            { "type","websocket" },{ "uri",$"wss://{host}/api/nexmo/socket"},{ "content-type","audio/l16;rate=16000"},{ "headers",new JObject {
                                    { "language",locale },{ "callerID","MY_NUMBER_HARDCODED_WHILE_TESTING" }
                                }
                            }
                        })
                    }
                };
                nccos.Add(nccoConnect);
                return Content(nccos.ToString(),"application/json");
            }

            [HttpPost("event")]
            public IActionResult EventHandler()
            {
                return Ok();
            }

            [HttpGet("socket")]
            public async Task GetAudio()
            {
                if (HttpContext.WebSockets.IsWebSocketRequest)
                {
                    _webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
                    await Echo(HttpContext,_webSocket);
                }
                else
                {
                    HttpContext.Response.StatusCode = 400;
                }
            }

            //copy Paste from the Sample Code
            private async Task Echo(HttpContext context,WebSocket webSocket)
            {
                var buffer = new byte[1024 * 4];
                //Breakpoint : ReceiveAsync generates an exception
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),CancellationToken.None);
                while (!result.CloseStatus.HasValue)
                {
                    await webSocket.SendAsync(new ArraySegment<byte>(buffer,result.Count),result.MessageType,result.EndOfMessage,CancellationToken.None);

                    result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),CancellationToken.None);
                }
                await webSocket.CloseAsync(result.CloseStatus.Value,result.CloseStatusDescription,CancellationToken.None);
            }
        }
    }

这里捕到的异常:

System.Net.WebSockets.WebSocketException (0x80004005): The remote
party closed the WebSocket connection without completing the close
handshake. —> System.Net.WebSockets.WebSocketException (0x80004005):
The remote party closed the WebSocket connection without completing
the close handshake.

更多例外:

at System.Net.WebSockets.ManagedWebSocket.ThrowIfEOFUnexpected(Boolean
throwOnPrematureClosure)
at System.Net.WebSockets.ManagedWebSocket.EnsureBufferContainsAsync(Int32
minimumrequiredBytes,CancellationToken cancellationToken,Boolean
throwOnPrematureClosure)
at System.Net.WebSockets.ManagedWebSocket.ReceiveAsyncPrivate[TWebSocketReceiveResultGetter,TWebSocketReceiveResult](Memory`1
payloadBuffer,
TWebSocketReceiveResultGetter resultGetter) at
System.Net.WebSockets.ManagedWebSocket.ReceiveAsyncPrivate[TWebSocketReceiveResultGetter,
TWebSocketReceiveResultGetter resultGetter) at
….Controllers.NexmoController.Echo(HttpContext context,
WebSocket webSocket) in
C:…\Controllers\NexmoController.cs:line
97 at ….Controllers.NexmoController.GetAudio() in
C:…\Controllers\NexmoController.cs:line
68 at lambda_method(Closure,Object ) at
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.AwaitableResultExecutor.Execute(IActionResultTypeMapper
mapper,ObjectMethodExecutor executor,Object controller,Object[]
arguments) at System.Threading.Tasks.ValueTask`1.get_Result() at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterasync()
at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&
next,Scope& scope,Object& state,Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterasync()
at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next,
Scope& scope,Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext
httpContext) at
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext
httpContext) at
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
context)

什么想法发生了什么?或者我如何解决这个问题?
我真的不明白这里的问题是什么.

我还尝试检查Websocket的WebSocketState,并将其设置为“Open”.
有关信息,我自己测试了示例代码(websocket回应用户的输入)并且它可以工作.

解决方法

我们找到了一个解决方案:

> ngrock不支持websockets(不是免费),所以我们在azure上发布了我们的应用程序.
>我们需要实例化websocket
StartUp而不是我们的控制器(如sample code
listed in the original post).我们已经采用了“Echo”方法
另一个类(更多是为了保持良好的结构)并设置它
静态的.

现在一切正常:)

澄清:ngrock不适用于安全的websockets(wss)

Go WebSocket 如何处理并发连接?

Go WebSocket 如何处理并发连接?

go websocket 处理并发连接的方法:为每个连接使用一个 goroutine。通过 channel 进行连接通信。使用第三方库(如 [gowebsocket](https://github.com/gobwas/ws)、[gorilla/websocket](https://github.com/gorilla/websocket))来简化处理。

Go WebSocket 如何处理并发连接?

Go WebSocket 如何处理并发连接

WebSocket 是一种全双工通信协议,允许客户端和服务器进行实时双向通信。Go 语言中处理 WebSocket 并发连接的常用方法如下:

1. Goroutine

一个简单的解决方案是为每个连接使用一个 Goroutine。Goroutine 是 Go 中的一种轻量级线程,可以并行执行。当一个新的 WebSocket 连接建立时,我们可以创建一个新的 Goroutine 来处理它:

package main

import (
    "fmt"
    "net/http"
    "os"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}

func main() {
    // WebSocket 服务器端口号
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 对请求进行 WebSocket 升级
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            fmt.Println(err)
            return
        }

        // 创建一个 Goroutine 处理连接
        go handleConnection(conn)
    })

    http.ListenAndServe(":"+port, nil)
}

// handleConnection 处理一个 WebSocket 连接
func handleConnection(conn *websocket.Conn) {
    for {
        msgType, msg, err := conn.ReadMessage()
        if err != nil {
            fmt.Println(err)
            break
        }

        if msgType == websocket.TextMessage {
            // 处理文本消息
            fmt.Println("Received text message:", string(msg))
            if err := conn.WriteMessage(msgType, msg); err != nil {
                fmt.Println(err)
            }
        } else {
            // 处理其他类型的消息
        }
    }

    conn.Close()
}
登录后复制

2. Channel

Channel 是 Go 中用于通信的并发通道。我们可以通过一个 Channel 来处理多个连接:

package main

import (
    "fmt"
    "net/http"
    "os"
    "sync"
    "time"

    "github.com/gorilla/websocket"
)

var (
    upgrader = websocket.Upgrader{}
    connections = make(chan *websocket.Conn, 100)
    wg sync.WaitGroup
)

func main() {
    // WebSocket 服务器端口号
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        // 对请求进行 WebSocket 升级
        conn, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            fmt.Println(err)
            return
        }

        // 将连接添加到 Channel
        connections <- conn
    })

    // 启动一个 Goroutine 处理 Channel 中的连接
    go handleConnections()

    http.ListenAndServe(":"+port, nil)
}

// handleConnections 处理 Channel 中的 WebSocket 连接
func handleConnections() {
    for {
        conn := <-connections

        wg.Add(1)
        go func() {
            defer wg.Done()
            for {
                msgType, msg, err := conn.ReadMessage()
                if err != nil {
                    fmt.Println(err)
                    break
                }

                if msgType == websocket.TextMessage {
                    // 处理文本消息
                    fmt.Println("Received text message:", string(msg))

                    // 向所有连接的客户端广播消息
                    for c := range connections {
                        if c != conn {
                            if err := c.WriteMessage(msgType, msg); err != nil {
                                fmt.Println(err)
                            }
                        }
                    }
                } else {
                    // 处理其他类型的消息
                }
            }

            conn.Close()
        }()
    }
}
登录后复制

通过管道传递连接可以在所有 Goroutine 之间共享连接,并避免创建过多线程带来的开销。

3. 第三方库

还有许多第三方库可以简化 WebSocket 并发处理,例如:

  • [gowebsocket](https://github.com/gobwas/ws)
  • [gorilla/websocket](https://github.com/gorilla/websocket)
  • [fasthttp/websocket](https://github.com/valyala/fasthttp/blob/master/websocket/websocket.go)

这些库提供了高级别的 API 来处理并发连接,并简化了 WebSocket 的使用。

以上就是Go WebSocket 如何处理并发连接?的详细内容,更多请关注php中文网其它相关文章!

Go WebSocket 如何处理断开连接?

Go WebSocket 如何处理断开连接?

go websocket 库提供 closehandler 机制来处理断开连接。当客户端关闭连接时,conn 类型触发 close 事件。使用 defer 语句注册 closehandler 函数可以监听该事件,接收 conn 和关闭原因常量。closehandler 函数被自动调用,提供处理断开连接和恢复应用程序的机会。

Go WebSocket 如何处理断开连接?

Go WebSocket:优雅地处理断开连接

在构建实时 Web 应用程序时,WebSocket 是一个强大的工具,用于在客户端和服务器之间进行双向通信。然而,处理客户端连接断开的情况至关重要,以保证应用程序的稳定性和可靠性。

处理断开连接

Go WebSocket 库为处理断开连接提供了内置机制。当客户端关闭连接时,[Conn](https://pkg.go.dev/github.com/gorilla/websocket#Conn) 类型会触发 Close 事件。

要监听此事件,可以使用 defer 语句将 [CloseHandler](https://pkg.go.dev/github.com/gorilla/websocket#CloseHandler) 函数注册到 WebSocket 连接:

import (
    "github.com/gorilla/websocket"
)

func handleConnection(ws *websocket.Conn) {
    defer ws.CloseHandler()(ws, websocket.CloseNormalClosure)
    // ...
}
登录后复制

CloseHandler 函数接受两个参数:*Conn 和一个表示关闭原因的常量(例如 websocket.CloseNormalClosure 表示正常关闭)。当连接被关闭时,该函数将被自动调用。

实战案例

以下是一个处理断开连接的简单实战案例:

package main

import (
    "fmt"
    "github.com/gorilla/websocket"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        ws, err := websocket.Upgrade(w, r, nil, nil, nil)
        if err != nil {
            fmt.Printf("upgrade error: %v", err)
            return
        }
        defer ws.CloseHandler()(ws, websocket.CloseNormalClosure)

        // 监听消息和断开连接事件
        go func() {
            for {
                _, _, err := ws.ReadMessage()
                if err != nil {
                    // 处理错误(例如连接断开)
                    return
                }
            }
        }()
    })

    http.ListenAndServe(":8080", nil)
}
登录后复制

在处理断开连接方面,CloseHandler 提供了一种简单而优雅的方式,可以帮助应用程序从客户端断开事件中恢复并继续正常运行。

以上就是Go WebSocket 如何处理断开连接?的详细内容,更多请关注php中文网其它相关文章!

我们今天的关于PHP棘轮websocket SSL连接?的分享已经告一段落,感谢您的关注,如果您想了解更多关于Android WebSocket中的SSL连接错误、c# – 在.Net Core中将Nexmo连接到Websocket失败(远程方关闭了WebSocket)、Go WebSocket 如何处理并发连接?、Go WebSocket 如何处理断开连接?的相关信息,请在本站查询。

本文标签: