Created
October 24, 2017 20:41
-
-
Save Flayed/0c820c57b24f8d8d5bc5529e4027389d to your computer and use it in GitHub Desktop.
TcpClient works
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); | |
| 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