[C#]Serial Port Send and Receive Data

Client Class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace COMClient
{
    public class COMClient
    {
        private SerialPort sp = null;

        public COMClient(string COM)
        {
            this.sp = new SerialPort(COM);
            // Open a new serial port connection
            this.sp.Open();
            // Discard data from the serial driver's receive buffer
            this.sp.DiscardInBuffer();
            // Discard data from the serial driver's transmit buffer
            this.sp.DiscardOutBuffer();
        }

        ~COMClient()
        {
            // Close the port connection
            this.sp.Close();
        }

        public void sendMsg(string msg)
        {
            // Write the specified number of bytes to the serial port using buffer data
            this.sp.WriteLine(msg);
        }
    }
}

Client call:

1
2
COMClient.COMClient com_client = new COMClient.COMClient("COM4");
com_client.sendMsg("Hello World!");

Server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace COM_Server
{
    class Program
    {
        static void Main(string[] args)
        {
            // Iterate through the serial port name array
            foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
            {
                Console.WriteLine(port);
            }

            byte[] b = new byte[32];
            SerialPort sp = new SerialPort("COM3");

            while (true)
            {
                // Open a new serial port connection
                sp.Open();
                // Discard data from the serial driver's receive buffer
                sp.DiscardInBuffer();
                // Discard data from the serial driver's transmit buffer
                sp.DiscardOutBuffer();
                // Read bytes from the serial input buffer and write them at the specified offset in a byte array
                string msg = sp.ReadLine();
                StringBuilder sb = new StringBuilder();
                Console.Write(msg);
                // Close the port connection
                sp.Close();
                // Suspend the current thread for 500 milliseconds
                System.Threading.Thread.Sleep(500);
            }
        }
    }
}

A virtual serial port is needed here — just install VSPD. Here we configure virtual serial ports COM3 and COM4:

QQ截图20170717221737

Server startup screenshot:

QQ截图20170717222051

Client sending screenshot:

QQ截图20170717222105

Server receiving screenshot:

QQ截图20170717222203