Skip to content

Add a port-forwarding example. #232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions examples/portforward/PortForward.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using k8s;
using k8s.Models;

namespace portforward
{
internal class Portforward
{
private static async Task Main(string[] args)
{
var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
IKubernetes client = new Kubernetes(config);
Console.WriteLine("Starting port forward!");

var list = client.ListNamespacedPod("default");
var pod = list.Items[0];
await Forward(client, pod);
}

private async static Task Forward(IKubernetes client, V1Pod pod) {
// Note this is single-threaded, it won't handle concurrent requests well...
var webSocket = await client.WebSocketNamespacedPodPortForwardAsync(pod.Metadata.Name, "default", new int[] {80}, "v4.channel.k8s.io");
var demux = new StreamDemuxer(webSocket);
demux.Start();

var stream = demux.GetStream((byte?)0, (byte?)0);

IPAddress ipAddress = IPAddress.Loopback;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(100);

Socket handler = null;

var accept = Task.Run(() => {
while (true) {
handler = listener.Accept();
var bytes = new byte[4096];
while (true) {
int bytesRec = handler.Receive(bytes);
stream.Write(bytes, 0, bytesRec);
if (bytesRec == 0 || Encoding.ASCII.GetString(bytes,0,bytesRec).IndexOf("<EOF>") > -1) {
break;
}
}
}
});

var copy = Task.Run(() => {
var buff = new byte[4096];
while (true) {
var read = stream.Read(buff, 0, 4096);
handler.Send(buff, read, 0);
}
});

await accept;
await copy;
}
}
}
13 changes: 13 additions & 0 deletions examples/portforward/portforward.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<ItemGroup>
<ProjectReference Include="..\..\src\KubernetesClient\KubernetesClient.csproj" />
</ItemGroup>

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<LangVersion>7.1</LangVersion>
</PropertyGroup>

</Project>