3

我已经按照这个这个这个教程在 .net 核心中构建了一个 WebSocket Web 应用程序。现在我正在尝试使用 Microsoft.AspNetCore.TestHost 对此进行一些集成测试

我创建 WebSocket 的方式

public static WebSocketClient StartWebSocketServer(string url)
{
    var baseAddress = $"http://{url}";
    var builder =
        WebHost.CreateDefaultBuilder(new string[]{})
            .UseEnvironment("Development")
            .ConfigureLogging((ctx, logging) => logging.AddConsole())
            .UseUrls(baseAddress)
            .UseStartup<SocketsTestStartup>();

    var server = new TestServer(builder);
    return server.CreateWebSocketClient();
}

并且 websocket 客户端的创建是在下面的代码中完成的

ClientWebSocket testAppClient = new ClientWebSocket();
await
    testAppClient 
    .ConnectAsync(
        new Uri("ws://loclahost:52015/local"),
        CancellationToken.None);

local是 websocket 服务器上的路径名

启动.cs

app.MapWebSocketManager(
    "/local",
    serviceProvider.GetService<LocalServiceSocketHandler>());

无论如何,连接会产生以下错误

System.Net.WebSockets.WebSocketException : Unable to connect to the remote server

我的问题是如何要求ClientWebSocket连接TestHost.WebSocketClient

4

3 回答 3

3

使用 TestServer 以下内容对我有用,以防万一它可以帮助其他人,这里是代码:

var builder = WebHost.CreateDefaultBuilder()
                .UseStartup<Startup>()
                .UseEnvironment("Development");

var server = new TestServer(builder);
var wsClient = server.CreateWebSocketClient();

var wsUri = new UriBuilder(server.BaseAddress) 
{
    Scheme = "ws"
}.Uri;

await wsClient.ConnectAsync(wsUri, CancellationToken.None);

但由于最初的问题是使用路径/local,因此只需要指定Path属性:

var wsUri = new UriBuilder(server.BaseAddress) 
{
    Scheme = "ws",

    Path = "local"
}.Uri;
于 2018-02-12T14:33:00.367 回答
3

我使用以下代码而不是 TestServer 来运行 WebSocket Web 应用程序

public static IWebHost CreateServer(int port)
{
    var configBuilder = new ConfigurationBuilder();
    configBuilder.AddInMemoryCollection();
    var config = configBuilder.Build();
    config["server.urls"] = $"http://localhost:{port}";

    var host = new WebHostBuilder()
        .ConfigureLogging((ctx, logging) => logging.AddDebug())
        .UseConfiguration(config)
        .UseKestrel()
        .UseStartup<SocketsTestStartup>()
        .Build();

    host.Start();

    return host;
}

基本上,我从aspnet/WebSockets测试中找到了解决方案

于 2017-11-21T10:31:50.237 回答
0

这段代码在我们开发的企业级应用程序中为我工作(在此处查看所有代码:https ://github.com/saturn72/Programmer )

//Create test server    
var server = new TestServer(builder);

//create websocket client, connect it and to server 
var wsc = server.CreateWebSocketClient();
var uri = new Uri(BaseUri, "ws");
var webSocket = wsc.ConnectAsync(uri, CancellationToken.None).Result;
var buffer = WebSocket.CreateClientBuffer(1024, 1024);

//Start receive data
Task.Run(()=> WebSocket.ReceiveAsync(_buffer, CancellationToken.None));

请记住async,您需要在测试中设置一些延迟

于 2018-05-08T08:10:47.843 回答