Created
October 24, 2017 20:35
-
-
Save Flayed/f233e73551f23a4906f3b7a21918f4ba to your computer and use it in GitHub Desktop.
TcpClient fail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private TcpClient client = new TcpClient(); | |
| public async Task<string> ConnectSendReceive(string message, int port) | |
| { | |
| Connect(port); | |
| await Write(message); | |
| return await Read(); | |
| } | |
| private void Connect(int port) | |
| { | |
| client.Connect(new IPEndPoint(IPAddress.Loopback, port)); | |
| } | |
| private async Task<string> Read() | |
| { | |
| using (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) | |
| { | |
| using (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