Vamos modificar o código do lado do servidor da seção anterior. O servidor passará a receber mensagens do cliente de forma contínua, além disso vamos habilitar o multithreading.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TcpServerDemo
{
public partial class Form1 : Form
{
private TcpListener listener;
private TcpClient tcpClient;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnStartServer_Click(object sender, EventArgs e)
{
Thread acceptThread = new Thread(() =>
{
IPAddress ip = IPAddress.Parse(this.textBoxIP.Text);//criar objeto de IP
listener = new TcpListener(ip, Convert.ToInt32(this.textBoxPort.Text));//criar objeto de escuta TCP
listener.Start();
this.textBoxInfo.Text = "Servidor iniciado‑" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
tcpClient = listener.AcceptTcpClient();//chamada bloqueante, aguardar conexão
this.textBoxInfo.Text = "Conexão estabelecida‑" + DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
NetworkStream stream = tcpClient.GetStream();
byte[] byteArray = new byte[1024];
while (true)
{
int length = stream.Read(byteArray, 0, 1024);//copia os bytes do fluxo para o buffer byteArray
//length representa o tamanho real dos bytes enviados pelo cliente
string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
this.textBoxInfo.Text = "Recebido:" + receiveMessage + "-" +
DateTime.Now.ToShortTimeString() + "\r\n" + this.textBoxInfo.Text;
}
});
acceptThread.IsBackground = true;
acceptThread.Start();
}
}
}Code language: C# (cs)
Implementação com WinForms + TcpClient / TcpListener:
O cliente envia textos personalizados continuamente para o servidor; digite 【Sair】para encerrar conexão e finalizar o programa
Esse exemplo resolve o travamento da interface causado por multithreads com uma abordagem simples, mas a forma correta é a seguinte:
Control.CheckForIllegalCrossThreadCalls = false;é uma solução grosseira não recomendada. Em projetos oficiais useInvoke/BeginInvokepara atualizar controles de threads diferentes.
1. Lado do servidor
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace TcpServerDemo
{
public partial class Form1 : Form
{
private TcpListener listener;
private TcpClient tcpClient;
public Form1()
{
InitializeComponent();
// Não use em projetos de produção, apenas para estudo
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnStartServer_Click(object sender, EventArgs e)
{
// Nova thread para evitar travamento da interface
new Thread(() =>
{
IPAddress ip = IPAddress.Parse(textBoxIP.Text);
listener = new TcpListener(ip, Convert.ToInt32(textBoxPort.Text));
listener.Start();
AppendLog($"Servidor iniciado‑{DateTime.Now.ToShortTimeString()}");
tcpClient = listener.AcceptTcpClient();
AppendLog($"Cliente conectado‑{DateTime.Now.ToShortTimeString()}");
NetworkStream stream = tcpClient.GetStream();
byte[] byteArray = new byte[1024];
while (true)
{
int length = stream.Read(byteArray, 0, 1024);
if (length <= 0)
{
AppendLog("Cliente encerrou a conexão");
break;
}
string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);
AppendLog($"Recebido:{receiveMessage} ‑{DateTime.Now.ToShortTimeString()}");
}
tcpClient.Close();
listener.Stop();
}).Start();
}
// Adiciona linha de log na caixa de texto
private void AppendLog(string msg)
{
textBoxInfo.Text = msg + "\r\n" + textBoxInfo.Text;
}
}
}Code language: C# (cs)
2. Código do cliente
Implementa entrada contínua; ao digitar “Sair” a comunicação é finalizada
Controles sugeridos para a interface do cliente:
textBoxServerIp:IP do servidortextBoxPort:Número da portatextBoxSend:Campo para digitar mensagens a serem enviadasbtnConnect:Botão de conexãobtnSend:Botão de envio
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TcpClientDemo
{
public partial class ClientForm : Form
{
private TcpClient client;
private NetworkStream stream;
private bool isConnected = false;
public ClientForm()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
// Conectar‑se ao servidor
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient();
client.Connect(textBoxServerIp.Text, Convert.ToInt32(textBoxPort.Text));
stream = client.GetStream();
isConnected = true;
MessageBox.Show("Conexão realizada, você já pode enviar mensagens!");
}
catch (Exception ex)
{
MessageBox.Show("Falha na conexão:" + ex.Message);
}
}
// Lógica principal para envio de mensagens
private void btnSend_Click(object sender, EventArgs e)
{
if (!isConnected)
{
MessageBox.Show("Conecte‑se ao servidor primeiro!");
return;
}
string content = textBoxSend.Text.Trim();
if (string.IsNullOrEmpty(content))
return;
// Verifica se comando de saída foi digitado
if (content == "Sair")
{
byte[] exitData = Encoding.Unicode.GetBytes(content);
stream.Write(exitData, 0, exitData.Length);
// Libera recursos
stream.Close();
client.Close();
isConnected = false;
MessageBox.Show("Conexão encerrada");
return;
}
// Envia conteúdo personalizado
byte[] data = Encoding.Unicode.GetBytes(content);
stream.Write(data, 0, data.Length);
textBoxSend.Clear();
}
}
}Code language: C# (cs)
static void Main(string[] args)
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 8899);
NetworkStream stream = client.GetStream();
while (true)
{
Console.Write("Digite o conteúdo para envio:");
string msg = Console.ReadLine();
byte[] buf = Encoding.Unicode.GetBytes(msg);
stream.Write(buf,0,buf.Length);
if (msg == "Sair")
{
stream.Close();
client.Close();
break;
}
}
}Code language: JavaScript (javascript)
Se quiser, posso reescrever todo o código com estrutura async/await totalmente assíncrona, eliminando completamente threads auxiliares e a prática inadequada de desligar a verificação entre threads.
Envio contínuo pelo cliente