当前位置:网站首页>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 :
边栏推荐
- Netease email (126/163): authorization code acquisition strategy
- G026-db-gs-ins-03 openeuler deployment opengauss (1 active and 2 standby or multiple standby)
- Introduction to bermudagrass
- Hard core innovation that database needs to care about in the future
- mysql源码分析——索引的数据结构
- MySQL write lock does not take effect
- 城市安全系列科普丨进入溺水高发期,救生常识话你知
- 【tf.keras】:版本从1.x升级到2.x遇到的一个问题:InvalidArgumentError: Cannot assign a device for operation embedding_
- After taking aiyouteng's medicine, Naifei's condition improved
- Exomeiser annotates and prioritizes exome variants
猜你喜欢

253 Conference Room II

MySQL学习笔记(总结)

Parse string

Withdrawal of IPO application, Yunzhou intelligent "tour" of unmanned boat enterprise fails to enter the science and Technology Innovation Board

Yolov3 trains its own data set

Adaptive design and responsive design

Leetcode 220. 存在重复元素 III
![[adaptiveavgpool3d] pytorch tutorial](/img/d0/60ee74ff554effa06084d5d01a03e1.png)
[adaptiveavgpool3d] pytorch tutorial

Dynamics 365: how to get the threshold value of executemullerequest in batch requests

iptables常用命令小清单
随机推荐
应用修改日志路径log4j.properties
253 Conference Room II
2.19 haas506 2.0开发教程 - bluetooth - 蓝牙通信(仅支持2.2以上版本)
Please talk about the financial products with a yield of more than 6%
torch_ How to use scatter. Scatter() in detail
R语言可视化分面图、多变量分组嵌套多水平t检验、并指定参考水平、可视化多变量分组嵌套多水平分面箱图(faceting boxplot)并添加显著性水平、指定显著性参考水平
Exomeiser annotates and prioritizes exome variants
Class assignment (6) - 575. Word division (word)
yolov3 训练自己的数据集
31 next spread
MySQL write lock does not take effect
[loj3247] [USACO 2020.1 platinum "non declining subsequences (DP, divide and conquer)
Leetcode 223. rectangular area
有了这个机器学习画图神器,论文、博客都可以事半功倍了!
安信证券开户在手机开户安全吗?
mysql源码分析——索引的数据结构
Using JS to implement click events
There are more than 20 categories of the four operators in MySQL. It took three days and three nights to sort them out. Don't collect them quickly
JUC源码学习笔记3——AQS等待队列和CyclicBarrier,BlockingQueue
2022/7/18 CF training