我已经按照this和this或this教程在.net核心中构建了一个WebSocket Web应用程序。现在我试图通过使用Microsoft.AspNetCore.TestHost
来对此进行一些集成测试我创建WebSocket的方式
String
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();
}
ClientWebSocket testAppClient = new ClientWebSocket();
await
testAppClient
.ConnectAsync(
new Uri("ws://loclahost:52015/local"),
CancellationToken.None);
是websocket服务器上的路径名
Startup.cs
local
无论如何,连接产生以下错误
app.MapWebSocketManager(
"/local",
serviceProvider.GetService<LocalServiceSocketHandler>());
我的问题是如何让System.Net.WebSockets.WebSocketException : Unable to connect to the remote server
与ClientWebSocket
联系?
答案 0 :(得分:2)
我使用以下代码运行WebSocket Web应用程序
,而不是TestServerpublic 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测试中找到了解决方案
答案 1 :(得分:1)
使用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;
答案 2 :(得分: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
,你需要在测试中设置一些延迟