This article introduces Socket Client programming.
The official example also includes SocketClient. However, the function is DNS resolution and website data reception. We need to greatly improve the communication between the SocketClient program and the Socket Server on the PC.
The code for connecting to the server function is as follows:
Private static Socket ConnectSocket (String ip, Int32 port)
{
Try
{
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Socket. Connect (new IPEndPoint (IPAddress. Parse (ip), port ));
Return socket;
}
Catch
{
Return null;
}
}
The main function code calls the connectSocket function. If the connection is successful, "hello. net micro framework!" is sent !!!", After sending the data, the system then receives the data from the server and sends it back directly. The relevant code is as follows.
While (true)
{
ServerSocket = ConnectSocket ("192.168.1.128", 8080 );
If (serverSocket! = Null)
{
String s = "hello. net micro framework !!! ";
Byte [] bytDatas = System. Text. UTF8Encoding. UTF8.GetBytes (s );
ServerSocket. Send (bytDatas );
While (true)
{
Try
{
Byte [] buffer = new Byte [1024];
If (serverSocket. Poll (5 * c_microsecondsPerSecond, SelectMode. SelectRead ))
{
If (serverSocket. Available = 0) return;
Int32 bytesRead = serverSocket. Receive (buffer, serverSocket. Available, SocketFlags. None );
Byte [] bytData = new byte [bytesRead];
Array. Copy (buffer, bytData, bytData. Length );
String ss = new string (System. Text. UTF8Encoding. UTF8.GetChars (bytData ));
Debug. Print (ss );
ServerSocket. Send (bytData );
}
}
Catch (SocketException se)
{
Debug. Print (se. ToString ());
Break;
}
}
}
Thread. Sleep (1000 );
}
Deploy the code on the Development Board and run it. Then open the Prepared TCP Server program (a TCP/UDP test tool I have compiled is as follows: http://www.sky-walker.com.cn/mfrelease/tools/yftcpserver.rar .)
The running program interface is as follows:
You can find that the client has been connected to the server and sent "hello. net micro framework !!!", We sent the data ". net micro framework" and found that the server has also returned the data sent.
When we open the serial port debugging program, we will also find the program on the Development Board and send the program received through the debug port, as shown in:
We have finished introducing basic network programming. You can easily compile network communication programs based on your actual needs.
Bytes --------------------------------------------------------------------------------------------------