当前位置:网站首页>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
边栏推荐
- 为租客提供帮助
- Parsing of XML files
- AI talent cultivation new ideas, this live broadcast has what you care about
- THINKPHP框架的优秀开源系统推荐
- [high frequency interview questions] difficulty 2.5/5, simple combination of DFS trie template level application questions
- NDK beginner's study (1)
- IP and long integer interchange
- MySQL "invalid use of null value" solution
- Laravel form builder uses
- docker部署oracle
猜你喜欢
"New red flag Cup" desktop application creativity competition 2022
Use day JS let time (displayed as minutes, hours, days, months, and so on)
Assign a dynamic value to the background color of DataGrid through ivalueconverter
Redis can only cache? Too out!
Details of redis core data structure & new features of redis 6
Leetcode simple question sharing (20)
2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array
Supply chain supply and demand estimation - [time series]
最长上升子序列模型 AcWing 1014. 登山
Introduction to database system - Chapter 1 introduction [conceptual model, hierarchical model and three-level mode (external mode, mode, internal mode)]
随机推荐
docker部署oracle
【日常训练--腾讯精选50】231. 2 的幂
Excuse me, why is it that there are no consumption messages in redis and they are all piled up in redis? Cerely is used.
交换机和路由器的异同
The meaning of variables starting with underscores in PHP
最长上升子序列模型 AcWing 482. 合唱队形
请问,如图,pyhon云函数提示使用了 pymysql模块,这个是怎么回事?
最长上升子序列模型 AcWing 1014. 登山
Battle Atlas: 12 scenarios detailing the requirements for container safety construction
[untitled]
Vscode configuration uses pylint syntax checker
Is it safe to open an account online now? Which securities company should I choose to open an account online?
Attribute keywords aliases, calculated, cardinality, ClientName
648. Word replacement: the classic application of dictionary tree
常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
The reason why data truncated for column 'xxx' at row 1 appears in the MySQL import file
Beginner XML
Verilog implementation of a simple legv8 processor [4] [explanation of basic knowledge and module design of single cycle implementation]
GVIM [III] [u vimrc configuration]
[daily training] 648 Word replacement