dotnet-installer/test/dotnet-projectmodel-server.Tests/DthTestServer.cs

53 lines
1.5 KiB
C#
Raw Normal View History

2015-12-09 17:57:45 +00:00
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Microsoft.DotNet.ProjectModel.Server.Tests
{
public class DthTestServer : IDisposable
{
private readonly ProjectModelServerCommand _program;
2015-12-09 17:57:45 +00:00
private readonly Thread _thread;
public DthTestServer()
2015-12-09 17:57:45 +00:00
{
Port = FindFreePort();
HostId = Guid.NewGuid().ToString();
_program = new ProjectModelServerCommand(Port, HostId);
2015-12-09 17:57:45 +00:00
_thread = new Thread(() => { _program.OpenChannel(); }) { IsBackground = true };
2015-12-09 17:57:45 +00:00
_thread.Start();
}
public string HostId { get; }
public int Port { get; }
public void Dispose()
{
try
{
_program.Shutdown();
}
catch (InvalidOperationException)
{
// swallow the exception if the process had been terminated.
}
}
private static int FindFreePort()
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
return ((IPEndPoint)socket.LocalEndPoint).Port;
}
}
}
}