ClientWebSocket-SocketException:无法建立连接 [英] ClientWebSocket - SocketException: No connection could be made

查看:202
本文介绍了ClientWebSocket-SocketException:无法建立连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ClientWebSocket连接到WebSocket服务器(演示或本地主机).我有一个例外:

I am trying to connect to WebSocket server (demo or localhost) using ClientWebSocket. I get an exception:

System.Net.WebSockets.WebSocketException
  HResult=0x80004005
  Message=Unable to connect to the remote server
  Source=System.Net.WebSockets.Client
  StackTrace:

Inner Exception 1:
HttpRequestException: No connection could be made because the target machine actively refused it

Inner Exception 2:
SocketException: No connection could be made because the target machine actively refused it

我也有成功连接的JavaScript websocket客户端.为什么我无法使用ClientWebSocket进行连接?

I also have JavaScript websocket client which connected succefully. Why I can't connect using ClientWebSocket?

using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using StreamJsonRpc;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            try
            {
                Console.WriteLine("Press Ctrl+C to end.");
                //await ConnectAsync("ws://localhost:63762/ws");
                await ConnectAsync("ws://demos.kaazing.com/echo");
                
            }
            catch (Exception ex)
            {
                  Console.WriteLine(ex);
                  Console.ReadKey();
            }
        }

        static async Task ConnectAsync(string url)
        {
            using (var socket = new ClientWebSocket())
            {
                Console.WriteLine("---> JSON-RPC Client connecting to " + url);

                await socket.ConnectAsync(new Uri(url), CancellationToken.None);
                Console.WriteLine("-> Connected to web socket. Establishing JSON-RPC protocol...");
                                                         
            }

        }
    }
}

推荐答案

更新24/07

我在nodejs中编写简单的WebSocket服务器以测试连接本地主机我的websocket Web客户端已成功连接但已控制台应用每次都无法连接.

I write simple WebSocket server in nodejs to test connection on localhost. My websocket web client connected successfully but console app failed to connect every time.

如果是这样,那就没有意义了.它对我有效.

If so, it doesn't make sense. It works on me.

.net 控制台应用程序中有 ws 客户端的代码.

There are codes of ws client in .net console application.

    static async Task Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        
        try
        {
            Console.WriteLine("Press Ctrl+C to end.");
            await ConnectAsync("ws://localhost:8080");
            //await ConnectAsync("ws://demos.kaazing.com/echo");

            Console.ReadLine();
        }
        catch (OperationCanceledException)
        {
            // This is the normal way we close.
        }

    }

    static async Task ConnectAsync(string url)
    {
        using (var socket = new ClientWebSocket())
        {
            Console.WriteLine("---> JSON-RPC Client connecting to " + url);

            await socket.ConnectAsync(new Uri(url), CancellationToken.None);
            Console.WriteLine("-> Connected to web socket. Establishing JSON-RPC protocol...");


            await Send(socket, "Hello from client.");
            await Receive(socket);

            await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "close", CancellationToken.None);

        }

    }

    static async Task Send(ClientWebSocket socket, string data) =>
await socket.SendAsync(Encoding.UTF8.GetBytes(data), WebSocketMessageType.Text, true, CancellationToken.None);


    static async Task Receive(ClientWebSocket socket)
    {
        var buffer = new ArraySegment<byte>(new byte[2048]);
        do
        {
            WebSocketReceiveResult result;
            using (var ms = new MemoryStream())
            {
                do
                {
                    result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                    ms.Write(buffer.Array, buffer.Offset, result.Count);
                } while (!result.EndOfMessage);

                if (result.MessageType == WebSocketMessageType.Close)
                    break;

                ms.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(ms, Encoding.UTF8))
                    Console.WriteLine(await reader.ReadToEndAsync());
            }
        } while (true);
    }

我的 node.js 服务器上带有websocket的ws代码.

There are ws codes of my node.js server with websocket.

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log(`Received message => ${message}`)
  })
  ws.send('Hello from server!')
})

console.log('Server running at ws://127.0.0.1:8080');



________________________________________________________________

ClientWebSocket 无法在Python中直接连接到 socket.io .



_______________________________________________________________

ClientWebSocket can not directly connect to socket.io in Python.

这里是 @Jim Stott的解决方案.在 CodePlex 上有一个项目(

Here is a solution from @Jim Stott. There is a project on CodePlex ( NuGet as well ) that is a C# client for socket.io.

示例客户风格:

socket.On("news", (data) =>    {
Console.WriteLine(data);
});

下面的问题也有很多方法可以满足您的需求.
通过c#与socket.io服务器通信

And also there are many ways to meet your needs from the question below.
Communicating with a socket.io server via c#

此处是有关 WebSocket与Socket.io 的文章

这篇关于ClientWebSocket-SocketException:无法建立连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆