WPF c#套接字收到的值(如果更改)

时间:2019-02-28 14:19:00

标签: c# wpf sockets asynchronous receiver

我有两个客户端/服务器应用程序,我制作了用于在两个应用程序之间接收和发送值的按钮,我想知道如果在两个应用程序中以及在应用程序启动时都发生了更改,该如何自动接收值(我收到两个值, 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);
    }

0 个答案:

没有答案