Skip to content

Instantly share code, notes, and snippets.

@Flayed
Created October 24, 2017 20:41
Show Gist options
  • Select an option

  • Save Flayed/0c820c57b24f8d8d5bc5529e4027389d to your computer and use it in GitHub Desktop.

Select an option

Save Flayed/0c820c57b24f8d8d5bc5529e4027389d to your computer and use it in GitHub Desktop.
TcpClient works
private TcpClient client = new TcpClient();
public async Task<string> ConnectSendReceive(string message, int port)
{
Connect(port);
await Write(message);
string response = await Read();
client.Close();
return response;
}
private void Connect(int port)
{
client.Connect(new IPEndPoint(IPAddress.Loopback, port));
}
private async Task<string> Read()
{
var stream = client.GetStream();
byte[] receiveBuffer = new byte[2048];
int length = await stream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length);
return Encoding.Default.GetString(receiveBuffer, 0, length);
}
private async Task Write(string message)
{
var stream = client.GetStream();
byte[] byteMessage = Encoding.Default.GetBytes(message);
await stream.WriteAsync(byteMessage, 0, byteMessage.Length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment