上位机–客户端程序撰写部分2022/10/01
验证可行性:通过NetAssist网络通信助手(发送与接收数据🆗),本地环回地址
客户端代码中加入了关闭连接的按键(在通信中位主动方)
#region TCP/IP 客户端
//创建Client套接字
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Thread ReceiveMsgThread;
/// <summary>
/// 连接服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Bt_Start_Click(object sender, EventArgs e)
{
//连接服务器需要传递服务器的ip地址与端口号
IPEndPoint point = new IPEndPoint(IPAddress.Parse(Cb_local_Ip.Text), int.Parse(Cb_local_Port.Text));
//连接服务器
//使用try catch 的原因:会遇到服务器端口号ip地址被占用的情况
try
{
client.Connect(point);
}
catch (Exception ex)
{
MessageBox.Show("与服务器连接失败" + ex);
}
MessageBox.Show("与服务器连接成功");
ReceiveMsgThread = new Thread(ReceiveMsg);
ReceiveMsgThread.Start();
//Task.Run(new Action(() =>
//{
// ReceiveMsg();
//}));
Bt_Start.Enabled = false;
}
/// <summary>
/// 接收消息(客户端接收服务器消息)
/// </summary>
/// <param name="client"></param>
private void ReceiveMsg()
{
while (true)
{
byte[] b = new byte[1024 * 1024 * 2];
int length = 0;
try
{
length = client.Receive(b);
}
catch
{
MessageBox.Show("服务器断开连接");
}
if (length > 0)
{
string msg = Encoding.Default.GetString(b, 0, length);
//将状态更新在信息栏中
this.BeginInvoke(new EventHandler(delegate
{
Tb_Msg_Show.AppendText(client + ":" + msg +"\r\n");
}));
}
}
}