无法在按钮单击时调用msdn异步客户端示例的发送和接收方法

时间:2014-09-16 07:08:42

标签: c# winforms asynchronous client msdn

在我上面的示例refferd的winform实现中,我有一个按钮来进行estalish连接,然后是两个文本字段,其中我放了一些字符串,当单击snd按钮时,应该将数据发送到服务器并且应该从服务器接收响应。 他们在clientstart中调用了send和receive,但是我想在按钮点击时调用它们。 但是不知道如何在button_click事件中指定这些方法的参数。 我试过但找不到解决办法......请给我一些提示......

**client winform**

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace client
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void lblServerIP_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        public class StateObject
        {
            // Client socket.
            public Socket workSocket = null;
            // Size of receive buffer.
            public const int BufferSize = 256;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
            // Received data string.
            public StringBuilder sb = new StringBuilder();

        }

        public class AsynchronousClient
        {
       //     public Form1 frm;

            // The port number for the remote device.
            private const int port = 8888;

            // ManualResetEvent instances signal completion.
            public static ManualResetEvent connectDone =
                new ManualResetEvent(false);
            public static ManualResetEvent sendDone =
                new ManualResetEvent(false);
            public static ManualResetEvent receiveDone =
                new ManualResetEvent(false);

            // The response from the remote device.
            private static String response = String.Empty;

            public static void StartClient()
            {

                // Connect to a remote device.
                try
                {

                    // Establish the remote endpoint for the socket.
                    // The name of the 
                    // remote device is "host.contoso.com".
                    //  IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
                    //IPAddress ipAddress = ipHostInfo.AddressList[0];
                    string ip = GetLocalIP();
                    IPAddress ipAddress = IPAddress.Parse(ip);
                    IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                    // Create a TCP/IP socket.
                    Socket client = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

                    // Connect to the remote endpoint.
                    client.BeginConnect(remoteEP,
                        new AsyncCallback(ConnectCallback), client);
                    connectDone.WaitOne();


                    // Release the socket.
                    //client.Shutdown(SocketShutdown.Both);
                    //client.Close();

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
            static public string GetLocalIP()
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1";
            }

            private static void ConnectCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the socket from the state object.
                    Socket client = (Socket)ar.AsyncState;

                    // Complete the connection.
                    client.EndConnect(ar);

                    Console.WriteLine("Socket connected to {0}",
                        client.RemoteEndPoint.ToString());

                    // Signal that the connection has been made.
                    connectDone.Set();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            public static void Receive(Socket client)
            {
                try
                {
                    // Create the state object.
                    StateObject state = new StateObject();
                    state.workSocket = client;

                    // Begin receiving the data from the remote device.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                          new AsyncCallback(ReceiveCallback), state);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            private static void ReceiveCallback(IAsyncResult ar)
            {
                try
                {


                    // Retrieve the state object and the client socket 
                    // from the asynchronous state object.
                    StateObject state = (StateObject)ar.AsyncState;
                    Socket client = state.workSocket;
                    state.sb = new StringBuilder();
                    // Read data from the remote device.
                    int bytesRead = client.EndReceive(ar);
                    //int bytesRead = client.BeginReceive();

                    if (bytesRead > 0)
                    {

                        // There might be more data, so store the data received so far.
                        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));


                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                            new AsyncCallback(ReceiveCallback), state);

                        // }
                        // else
                        // {
                        // All the data has arrived; put it in response.
                        if (state.sb.Length > 1)
                        {
                            response = state.sb.ToString();

                        }
                        // Signal that all bytes have been received.
                        receiveDone.Set();
                    }
                    Form1 frm = new Form1();

                    frm.txtResponse.Text=response;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            public static void Send(Socket client, String data)
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);

                // Begin sending the data to the remote device.
                client.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), client);
            }

            private static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    // Retrieve the socket from the state object.
                    Socket client = (Socket)ar.AsyncState;

                    // Complete sending the data to the remote device.
                    int bytesSent = client.EndSend(ar);
                    //Console.WriteLine("Sent {0} bytes to server.", bytesSent);

                    // Signal that all bytes have been sent.
                    sendDone.Set();
                }
                catch (Exception e)
                {
                  MessageBox.Show(e.ToString());
                }
            }

            //public static int Main(String[] args)
            //{
            //    StartClient();
            //    Console.ReadLine();
            //    return 0;
            //}
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            //AsynchronousClient clnt = new AsynchronousClient();
            //string PrivateID = txtIMPI.Text;
            //string PublicID = txtIMPU.Text;
            //string data = PrivateID + ";" + PublicID;
            //for (int i = 0; i < 1; i++)
            //{
            //    Thread th = new Thread(new ThreadStart(AsynchronousClient.Send));
            //    th.Start();
            //    //Send(client, data);
            //}
            //sendDone.WaitOne();

            //// Receive the response from the remote device.
            //Receive(client);
            //receiveDone.WaitOne();

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //AsynchronousClient syn = new AsynchronousClient();
            //syn.frm = this;
            Thread thread = new Thread(new ThreadStart(AsynchronousClient.StartClient));
            thread.Start();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的意思是IP和端口号吗?它们在AsynchronousClient类中定义,您无法修改它们,因为它们被定义为private const

您必须修改AsynchronousClient类的实现,将它们公开为公共属性。

public class AsynchronousClient
{
    // The port number for the remote device.
    private int port = 8888;
    public int Port 
    { 
        get { return port; } 
        set { port = value;}
    }
    // The IP Address of the remote device
    private string ipAddress;
    public string IpAddress
    {
        get { return ipAddress; } 
        set { ipAddress= value;}         
    }
    ....  
}

然后在按钮的Click事件处理程序中,您可以像这样设置它们

private void btnConnect_Click(object sender, EventArgs e)
{
    AsynchronousClient client = new AsynchronousClient();
    client.Port = Int32.Parse(tbPort.Text);
    client.IpAddress = tbAddress.Text;

    //then connect to the remote device and send data
    //client.Connect();
    //client.Send(data);  
 }