GVKun编程网logo

Websocket SSL连接(websocket stomp连接)

10

对于WebsocketSSL连接感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解websocketstomp连接,并且为您提供关于AndroidWebSocket中的SSL连接错误、c–如何

对于Websocket SSL连接感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解websocket stomp连接,并且为您提供关于Android WebSocket中的SSL连接错误、c – 如何使用debug构建libwebsockets(即-g所以我可以使用gdb)? (我在libwebsockets函数上遇到段错误,ssl_ctrl())、c# – System.Net.Sockets.SocketException创建websocket连接时、c# – 在.Net Core中将Nexmo连接到Websocket失败(远程方关闭了WebSocket)的宝贵知识。

本文目录一览:

Websocket SSL连接(websocket stomp连接)

Websocket SSL连接(websocket stomp连接)

我正在尝试测试安全的网络套接字,但是遇到了麻烦。这是我的测试:

var WebSocket = require(''ws'');describe(''testing Web Socket'', function() {  it(''should do stuff'', function(done) {    var ws = new WebSocket(''wss://localhost:15449/'', {      protocolVersion: 8,      origin: ''https://localhost:15449''    });    ws.on(''open'', function() {      console.log(''open!!!'');      done();    });    console.log(ws);  });});

创建后,这是“ ws”的日志:

{ domain: null,  _events: { open: [Function] },  _maxListeners: undefined,  _socket: null,  _ultron: null,  _closeReceived: false,  bytesReceived: 0,  readyState: 0,  supports: { binary: true },  extensions: {},  _isServer: false,  url: ''wss://localhost:15449/'',  protocolVersion: 8 }

我没有从打开回来的日志。我正在本地运行该项目,并且当我使用Chrome Advanced Rest Client工具时,可以正常连接。

我想念什么吗?请帮忙。

编辑: 我添加ws.on(''error'')并注销,{ [Error: self signed certificate] code:''DEPTH_ZERO_SELF_SIGNED_CERT'' }
我也尝试遵循此代码,但得到相同的错误。

答案1

小编典典

https模块正在拒绝您的自签名证书(正如人们希望的那样)。您可以通过传递一个rejectUnauthorized:false选项(WebSocket将传递给https)来强制其停止检查:

var ws = new WebSocket(''wss://localhost:15449/'', {  protocolVersion: 8,  origin: ''https://localhost:15449'',  rejectUnauthorized: false});

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 – 如何使用debug构建libwebsockets(即-g所以我可以使用gdb)? (我在libwebsockets函数上遇到段错误,ssl_ctrl())

c – 如何使用debug构建libwebsockets(即-g所以我可以使用gdb)? (我在libwebsockets函数上遇到段错误,ssl_ctrl())

供您参考(因为我在下面提到了库函数),可以在这里找到libwebsockets文档: https://github.com/warmcat/libwebsockets/blob/master/libwebsockets-api-doc.html#L466

网站可以在这里找到:http://libwebsockets.org/trac/libwebsockets

我的问题是,如果我为libwebsocket_client_connect()函数的ssl_connection参数传入1或2,我会得到一个段错误.

我的代码用c写的.

想要找出它发生的位置,我在gdb中运行了我的代码(在添加了-g标志之后).在segfault之后,我跑了回溯.这就是我得到的:

来自/lib/x86_64-linux-gnu/libssl.so.1.0.0的SSL_ctrl()中的0x00007ffff7748c43
(gdb)回溯

来自/lib/x86_64-linux-gnu/libssl.so.1.0.0的SSL_ctrl()中的0 0x00007ffff7748c43

来自/usr/local/lib/libwebsockets.so.5.0.0的lws_client_socket_service()中的1 0x00007ffff7503aa2

来自/usr/local/lib/libwebsockets.so.5.0.0的libwebsocket_service_fd()中的2 0x00007ffff74fe606

来自/usr/local/lib/libwebsockets.so.5.0.0的libwebsocket_client_connect_2()中的3 0x00007ffff7504029

来自/usr/local/lib/libwebsockets.so.5.0.0的lws_client_socket_service()中的4 0x00007ffff75037d5

来自/usr/local/lib/libwebsockets.so.5.0.0的libwebsocket_service_fd()中的5 0x00007ffff74fe606

来自/usr/local/lib/libwebsockets.so.5.0.0的lws_plat_service()中的6 0x00007ffff7505980

还有更多,但相关信息高于……

如上所示,segfault发生在SSL_ctrl()函数中.

如果有人从libwebsockets SSL_ctrl()函数获得了段错误并解决了它,请告诉我.

如果有人可以告诉我如何使用调试标志构建libwebsockets(使用make,cmake或其他方式)和/或使它以冗长的方式写入某个日志文件和/或使其成为可能,我可以使用gdb进入函数,我非常感谢!

解决方法

要使用DEBUG选项构建libwebsockets,请在Cmake中使用-DCMAKE_BUILD_TYPE = DEBUG参数.

请确保删除所有早期版本的libwebsockets.h(使用-DCMAKE_BUILD_TYPE = DEBUG选项构建)并使用-DCMAKE_BUILD_TYPE = DEBUG参数进行干净构建.

在此之后启用调试时执行使用-d选项设置为日志级别

如果我的可执行文件是sock,那么在运行use时启用调试日志
     ./sock 127.0.0.1 -p 9000 -d 65535

这将产生类似的输出

[1449754712:6654] CLIENT: lws_client_connect: direct conn
    [1449754712:6654] CLIENT: lws_client_connect_2
    [1449754712:6654] CLIENT: lws_client_connect_2: address 127.0.0.1
    Reason :35
    Reason :32
    Reason :36
    [1449754712:6655] CLIENT: nonblocking connect retry

c# – System.Net.Sockets.SocketException创建websocket连接时

c# – System.Net.Sockets.SocketException创建websocket连接时

我是websocket的新手.我在.net 4.5框架中创建了一个控制台应用程序,并使用库“WebSocketSharp”创建了一个示例websocket客户端.我有以下代码

using System;
using WebSocketSharp;


namespace WebsocketTest
{
    class Program
    {
        public static void Main(string[] args)
        {
            try
            { 
            using (var ws = new WebSocketSharp.WebSocket("ws://192.168.18.186:7884"))
            {
               Console.WriteLine("started");
                ws.Connect();
                ws.Send("START");
                Console.ReadLine();
                }
            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }

        }
    }
}

但是我无法创建与在另一台机器上运行的websocket服务器的连接.我收到这样的错误信息

09-05-2017 16:20:41|Fatal|WebSocket.connect:0|System.Net.sockets.socketException (0x80004005): No connection Could be made because the target machine actively refused it 192.168.18.186:7884
                             at System.Net.sockets.TcpClient..ctor(String hostname,Int32 port)
                             at WebSocketSharp.WebSocket.setClientStream()
                             at WebSocketSharp.WebSocket.doHandshake()
                             at WebSocketSharp.WebSocket.connect()

与我的代码有关的问题是什么?有什么好的websocket库可用吗?

解决方法

查找代码是否存在问题的最简单方法是使用任何支持Web套接字的浏览器尝试连接到端点,并查看会发生什么.如果不确定,你也可以只使用telnet – 因为web-socket开始是一个文本协议(http 1.1标题)而你没有使用SSL,你应该只能打开一个连接并发送一些虚拟标题.如果telnet无法连接:您的代码将无法连接.

如果telnet可以连接,则客户端lib可能存在问题.实际上有一个内置于.NET中的Web套接字客户端,您应该可以使用它(ClientWebSocket)

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)

今天关于Websocket SSL连接websocket stomp连接的分享就到这里,希望大家有所收获,若想了解更多关于Android WebSocket中的SSL连接错误、c – 如何使用debug构建libwebsockets(即-g所以我可以使用gdb)? (我在libwebsockets函数上遇到段错误,ssl_ctrl())、c# – System.Net.Sockets.SocketException创建websocket连接时、c# – 在.Net Core中将Nexmo连接到Websocket失败(远程方关闭了WebSocket)等相关知识,可以在本站进行查询。

本文标签: