Сценарий - это когда пользователь нажимает кнопку подключения, он подключается к серверу и начинает получать пакеты с этого сервера. Пакеты < /p>
Код: Выделить всё
private async void buttonConnect_Click(object sender, EventArgs e)
{
try
{
buttonConnect.Enabled = false;
buttonListen.Enabled = false;
_client = new TcpClient();
await _client.ConnectAsync("localhost", 51111);
_stream = _client.GetStream();
readLoop(_client);
}
catch (Exception ex)
{
textBoxOutput.AppendText($"Connect Error: {ex.Message}\r\n");
}
}
async Task readLoop(TcpClient client)
{
try
{
byte[] data = new byte[5000];
while (true)
{
int byteRead = await _stream.ReadAsync(data, 0, data.Length);
if(byteRead == 0)
{
textBoxOutput.AppendText("Connection closed by the other side.\r\n");
break;
}
string message = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0');
textBoxOutput.AppendText($"Received: {message}\r\n");
}
}
catch (Exception ex)
{
textBoxOutput.AppendText($"Read Error: {ex.Message}\r\n");
}
}
private async void buttonConnect_Click(object sender, EventArgs e)
{
try
{
buttonConnect.Enabled = false; // Disable connect button while connecting
buttonListen.Enabled = false; // Disable listen button while connecting
_client = new TcpClient();
await _client.ConnectAsync("localhost", 999);
_stream = _client.GetStream();
Thread receiver = new Thread(new ThreadStart(readLoop));
receiver.Start();
}
catch (Exception ex)
{
textBoxOutput.AppendText($"Connect Error: {ex.Message}\r\n");
}
}
void readLoop()
{
try
{
byte[] data = new byte[5000];
while (true)
{
//consider thread safety later for now
int byteRead = _stream.Read(data, 0, data.Length);
if (byteRead == 0)
{
//consider thread safety later for now
textBoxOutput.AppendText("Connection closed by the other side.\r\n");
break;
}
string message = System.Text.Encoding.UTF8.GetString(data).TrimEnd('\0');
//consider thread safety later for now
textBoxOutput.AppendText($"Received: {message}\r\n");
}
}
catch (Exception ex)
{
//consider thread safety later for now
textBoxOutput.AppendText($"Read Error: {ex.Message}\r\n");
}
}
< /code>
Какой из этих вариантов лучше? < /p>
Я думаю, что первый кандидат лучше в безопасности потока. Нет необходимости использовать безопасную систему данных потока. Я не знаю ...
Подробнее здесь: https://stackoverflow.com/questions/796 ... -is-better
Мобильная версия