WPF c # сокет получил значение, если изменилось - PullRequest
0 голосов
/ 28 февраля 2019

У меня есть два клиент-серверных приложения, я сделал кнопки для получения и отправки значений между двумя приложениями, я хотел бы знать, как получить значение автоматически, если оно изменяется в обоих приложениях и при запуске приложения (Я получаю два значения: bool и int ).

Сервер

    public static IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
    public static TcpListener server = new TcpListener(ip, 8080);
    public static TcpClient client = default(TcpClient);

    // Stock value interface
    public static string val_interface ;

    async void buttonConnect_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            server.Start();


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }



     private void Button_receiver__Click(object sender, RoutedEventArgs e)
    {


            // receiver value

            client = server.AcceptTcpClient();


            byte[] receivedBuffer = new byte[100];
            NetworkStream stream = client.GetStream();

            stream.Read(receivedBuffer, 0, receivedBuffer.Length);

            StringBuilder msg = new StringBuilder();

            foreach (byte b in receivedBuffer)
            {

                string r = msg.Append(Convert.ToChar(b).ToString()).ToString();

                // last line

                 if(receivedBuffer.LastOrDefault().Equals(b))
                      {
                          ;                           
                        r = r.Substring(0, r.Length - 1);                            
                        if(r.ToString().Length < 2)
                          {
                                if(r.ToString() == "1")
                                {

                                    val_interface = r.ToString();


                                }
                                if(r.ToString() == "0")
                                {

                                    val_interface = r.ToString();

                                }                                                           
                              break;         
                          }
                           else
                          {

                              val_interface = r.ToString();
                              break;
                          }                            
                      }                    
          }                       
                System.Diagnostics.Debug.WriteLine(msg.ToString());

    }

    private void btn_send_Click(object sender, RoutedEventArgs e)
    {
            client = server.AcceptTcpClient();
            NetworkStream stream = client.GetStream();
            string r = val_interface;
            int byteCount = Encoding.ASCII.GetByteCount(r);
            byte[] sendData = new byte [100];
            sendData = Encoding.ASCII.GetBytes(r);
            stream.Write(sendData, 0, sendData.Length);


        stream.Close();
        client.Close();

    }

Клиент

    public static IPAddress ip = Dns.GetHostEntry("localhost").AddressList[0];
    TcpListener server = new TcpListener(ip, 8080);
    public static TcpClient client = default(TcpClient);

    // information de la connexion
    string serverIP = "localhost";
    int port = 8080;



    // same methods ...

Класс

public class MyClass
{

    public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
    {
        int startTickCount = Environment.TickCount;
        int sent = 0;  // how many bytes is already sent
        do
        {
            if (Environment.TickCount > startTickCount + timeout)
                throw new Exception("Timeout.");
            try
            {
                sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.WouldBlock ||
                    ex.SocketErrorCode == SocketError.IOPending ||
                    ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                {
                    // socket buffer is probably full, wait and try again
                    Thread.Sleep(30);
                }
                else
                    throw ex;  // any serious error occurr
            }
        } while (sent < size);
    }

    public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
    {
        int startTickCount = Environment.TickCount;
        int received = 0;  // how many bytes is already received
        do
        {
            if (Environment.TickCount > startTickCount + timeout)
                throw new Exception("Timeout.");
            try
            {
                received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.WouldBlock ||
                    ex.SocketErrorCode == SocketError.IOPending ||
                    ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                {
                    // socket buffer is probably empty, wait and try again
                    Thread.Sleep(30);
                }
                else
                    throw ex;  // any serious error occurr
            }
        } while (received < size);
    }
...