当前位置:网站首页>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  

 

 

原网站

版权声明
本文为[Peacock Flying Southeast - Shenzhen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071209533121.html