当前位置:网站首页>C TCP client form application asynchronous receiving mode
C TCP client form application asynchronous receiving mode
2022-07-24 16:00:00 【luobeihai】
1. Program interface design
Probably design a simple interface as follows .![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Rq7GgnZv-1658637960222)(../picture/image-20220724124105799.png)]](/img/90/ad1f30d81e630460d9284efecbb9e5.png)
2. Core code of each part
2.1 Connect server
When the request connection button is pressed , Will trigger a click event , Then make the connection server request .
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
if (IsConnected == false)
{
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create a Socket Socket
IPAddress ipaddress = IPAddress.Parse(cbbHostIP.Text);
EndPoint point = new IPEndPoint(ipaddress, int.Parse(tbHostPort.Text));
tcpClient.Connect(point);
tcpClient.BeginReceive(recieveBuffer, 0, recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
IsConnected = true;
btnConnect.Text = " disconnect ";
}
else
{
tcpClient.Disconnect(false);
IsConnected = false;
btnConnect.Text = " Request connection ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
When pressing connect , So let's create one socket Socket , Then get the server of user input from the control IP And port , Then connect .
most important of all , Here is the asynchronous receiving design , Set the receive callback function ReceiveCallback.
2.2 send data
Because sending data , It is the user who actively presses “ send out ” Button sent , So it's simpler , As long as there is a click event of pressing the send button , Just send the data .
private void btnSend_Click(object sender, EventArgs e)
{
if (IsConnected == true)
{
tcpClient.Send(tbSend.Text.GetBytes("GBK"));
}
else
{
MessageBox.Show(" Please connect the server first ");
}
}
2.3 receive data
The received data is received asynchronously , Because it is impossible to determine when the server will send data to the client .
private void ReceiveCallback(IAsyncResult AR)
{
// Check how much bytes are recieved and call EndRecieve to finalize handshake
try
{
int recieved = tcpClient.EndReceive(AR);
if (recieved <= 0)
return;
string message = Encoding.GetEncoding("GBK").GetString(recieveBuffer, 0, recieved); // Only convert the received data
Print(message);
// Start receiving again
tcpClient.BeginReceive(recieveBuffer, 0, recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (SocketException ex)
{
MessageBox.Show(ex.ToString());
}
}
among ,ReceiveCallback Function is the callback function received . If there is data reception , Then the process of actually receiving data , It is completed in this callback function .
3. The source code of the whole project
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Net_assistance
{
public partial class Form1 : Form
{
public static Socket tcpClient;
bool IsConnected = false;
private byte[] recieveBuffer = new byte[8142];
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
// Get locally available IP Address
string strHostIP = Dns.GetHostName();
IPAddress[] ipadrlist = Dns.GetHostAddresses(strHostIP);
foreach (IPAddress ipaddr in ipadrlist)
{
if (ipaddr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
cbbHostIP.Items.Add(ipaddr.ToString());
}
cbbHostIP.Items.Add("127.0.0.1"); // Finally, add the loopback test address
cbbHostIP.SelectedIndex = 0;
tbHostPort.Text = "8080";
tbSend.Text = "hello world!";
}
private void Print(string msg)
{
tbRecv.AppendText($"[{
DateTime.Now.ToString("yyy-MM-dd HH.mm.ss.fff")}] {
msg}\r\n");
}
private void ReceiveCallback(IAsyncResult AR)
{
// Check how much bytes are recieved and call EndRecieve to finalize handshake
try
{
int recieved = tcpClient.EndReceive(AR);
if (recieved <= 0)
return;
string message = Encoding.GetEncoding("GBK").GetString(recieveBuffer, 0, recieved); // Only convert the received data
Print(message);
// Start receiving again
tcpClient.BeginReceive(recieveBuffer, 0, recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (SocketException ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
if (IsConnected == false)
{
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Create a Socket Socket
IPAddress ipaddress = IPAddress.Parse(cbbHostIP.Text);
EndPoint point = new IPEndPoint(ipaddress, int.Parse(tbHostPort.Text));
tcpClient.Connect(point);
tcpClient.BeginReceive(recieveBuffer, 0, recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
IsConnected = true;
btnConnect.Text = " disconnect ";
}
else
{
tcpClient.Disconnect(false);
IsConnected = false;
btnConnect.Text = " Request connection ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (IsConnected == true)
{
tcpClient.Send(tbSend.Text.GetBytes("GBK"));
}
else
{
MessageBox.Show(" Please connect the server first ");
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (IsConnected == true)
{
// When you close a window , If you are connecting to the server , Then disconnect and exit
tcpClient.Disconnect(false);
}
}
}
}
4. test
First open a server with the network debugging assistant . as follows :
Then open the client program written by ourselves , Enter the... Of the server IP And port after , Click to connect . At this time, you can see that the server detects the access of the client , Then we can send and receive data from each other , The effect is as follows :
边栏推荐
- Leetcode 223. 矩形面积
- Knowledge points of MySQL (12)
- [SWT] user defined data table
- 【洛谷】P1908 逆序对
- [acwing] 909. Chess game
- Dynamics 365: how to get the authentication information required to connect to D365 online from azure
- Netease email (126/163): authorization code acquisition strategy
- Arduino IDE ESP32固件安装和升级教程
- Do you understand the working principle of gyroscope?
- R language Visual facet chart, multivariable grouping nested multilevel t-test, and specify reference level, visual multivariable grouping nested multilevel faceting boxplot, and add significance leve
猜你喜欢

From which dimensions can we judge the quality of code? How to have the ability to write high-quality code?

Simplified understanding: publish and subscribe

Memorythrashing: Tiktok live broadcast to solve memory dithering practice

城市安全系列科普丨进入溺水高发期,救生常识话你知

Adaptive design and responsive design

How to choose the appropriate data type for fields in MySQL?

Will the capital market be optimistic about TCL's folding screen story?

Yolov6 trains its own data set

Knowledge points of MySQL (12)

Yolov3 trains its own data set
随机推荐
AttributeError: module ‘seaborn‘ has no attribute ‘histplot‘
[tf.keras]: a problem encountered in upgrading the version from 1.x to 2.x: invalidargumenterror: cannot assign a device for operation embedding_
287 finding duplicates
Dynamics 365: how to get the threshold value of executemullerequest in batch requests
Yolov4 trains its own data set
Leetcode 220. 存在重复元素 III
What is a firewall? What role can firewalls play?
Scala functions and their higher-order applications
Arduino ide esp32 firmware installation and upgrade tutorial
在LAMP架构中部署Zabbix监控系统及邮件报警机制
【ACWing】909. 下棋游戏
3、 Set foundation ArrayList set and simple student management system
【SWT】自定义数据表格
微调LayoutLM v3进行票据数据的处理和内容识别
Research on the efficiency of numpy array access
If this.$router Push the same address with different parameters, and the page does not refresh
请问好的券商的排名?网上开户安全吗
Public and private key transmission, and understanding of CA certificate
Which is a good noise reduction Bluetooth headset? Ranking of the most cost-effective noise reduction Bluetooth headsets
Deploy ZABBIX monitoring system and email alarm mechanism in lamp architecture