当前位置:网站首页>C # use TCP protocol to establish connection
C # use TCP protocol to establish connection
2022-07-07 14:12:00 【Peacock Flying Southeast - Shenzhen】
background : There is one deployed in Raspberry pie A server on Need to use windows The system is connected The data format is json Format So this article only has the client code :
1 Declare a global variable
Socket socket = null;
2 stay mainWindow Write in :
IPAddress ipadr = IPAddress.Parse("192.168.2.42"); //---ip The address is the server address
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
socket.Connect(ipadr,1616); //------------ It depends on whether the server has set the port number
}catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(" Failed to connect to server Please press enter to exit !");
return;
}
3 Button trigger event
private void Button_Click(object sender, RoutedEventArgs e)
{
//---- Definition json data format
Comand com = new Comand(); //------ You need to define additional classes Class has two properties All are string type
com.SendCmd = "1";
com.msg = "null";
string jsonData = JsonConvert.SerializeObject(com); //---- Need extra in The package manager console imports packages Otherwise, the report will be wrong
socket.Send(Encoding.ASCII.GetBytes(jsonData));
try
{
Thread receiveThread = new Thread(ReceiveMessage); //---- The method of receiving messages is defined below
receiveThread.Start(receiveThread);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
4 ReceiveMessage Method
public void ReceiveMessage(object obj)
{
try
{
byte[] bt = new byte[1024];
int len = socket.Receive(bt);
string data = Encoding.ASCII.GetString(bt,0,len);
listBox.Dispatcher.BeginInvoke( //---- Start delegation
new Action(() => { listBox.Items.Add("\r\n Received data :" + data);}),null);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(" Accept failure Please confirm whether it is disconnected !");
// receiveSocket.Shutdown(SocketShutdown.Both);
// receiveSocket.Close();
return;
}
}
ps: There is a drawback Raspberry pie There will be a black screen You need to restart the software when you open it again windows Here, write the connection in the main method That means the raspberry pie reopens here windows The software should also be reopened Reconnect the This is a bad point
边栏推荐
- Supply chain supply and demand estimation - [time series]
- [high frequency interview questions] difficulty 2.5/5, simple combination of DFS trie template level application questions
- gvim【三】【_vimrc配置】
- 属性关键字Aliases,Calculated,Cardinality,ClientName
- Excellent open source system recommendation of ThinkPHP framework
- 高等數學---第八章多元函數微分學1
- The meaning of variables starting with underscores in PHP
- Cargo placement problem
- . Net core about redis pipeline and transactions
- SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
猜你喜欢
GVIM [III] [u vimrc configuration]
js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
Parsing of XML files
Introduction to database system - Chapter 1 introduction [conceptual model, hierarchical model and three-level mode (external mode, mode, internal mode)]
常用数字信号编码之反向不归零码码、曼彻斯特编码、差分曼彻斯特编码
libSGM的horizontal_path_aggregation程序解读
566. Reshaping the matrix
Mathématiques avancées - - chapitre 8 différenciation des fonctions multivariables 1
通过 iValueConverter 给datagrid 的背景颜色 动态赋值
AI talent cultivation new ideas, this live broadcast has what you care about
随机推荐
3D Detection: 3D Box和点云 快速可视化
.net core 关于redis的pipeline以及事务
Oracle advanced (V) schema solution
Huawei image address
Help tenants
Excellent open source system recommendation of ThinkPHP framework
Beginner XML
Realization of search box effect [daily question]
Attribute keywords aliases, calculated, cardinality, ClientName
[Reading stereo matching papers] [III] ints
手把手教会:XML建模
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
Mathématiques avancées - - chapitre 8 différenciation des fonctions multivariables 1
MySQL "invalid use of null value" solution
Seven propagation behaviors of transactions
股票开户首选,炒股交易开户佣金最低网上开户安全吗
mysql导入文件出现Data truncated for column ‘xxx’ at row 1的原因
内存溢出和内存泄漏的区别
Is it safe to open an account online now? Which securities company should I choose to open an account online?
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)