繁体   English   中英

异步客户端套接字:如何将其他数据传递到服务器?

[英]Asynchronous Client Socket: How to pass additional data to server?

我正在研究使用异步客户端服务器套接字的MSDN示例代码。 我知道在建立新的客户端连接时情况如何。

但是,如果客户端已经连接并且想要将一些新数据传递到服务器(或其他客户端),该怎么办?

这是我到目前为止的内容:

public partial class Form1 : Form
{
    AsynchronousClient ac;
    public Form1()
    {
        InitializeComponent();            
    }

    private void buttonLogin_Click(object sender, EventArgs e)
    {
        buttonLogin.Enabled = false;
        new Thread(new ThreadStart(CreatingConnection)).Start();
    }

    private void CreatingConnection()
    {
        ac = new AsynchronousClient();
        ac.SendingMessage += (msg) => AC_SendingMassage(msg);
        ac.StartClient();
    }

    private void AC_SendingMassage(string message)
    {
        listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(message); });
    }

    private void buttonData_Click(object sender, EventArgs e)
    {
        string message = textBox1.Text;
        //TODO:
        //how to send data from here (including whats in textBox)??
    }
}

这是msdn的示例中的代码(2个类)(仅适用于客户端):

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    public event Action<string> SendingMessage;
    // The port number for the remote device.
    private const int port = 11000;

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

    // The response from the remote device.
    private string response;

    public void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            string ip = "192.168.1.101";
            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();

            // Send test data to the remote device.
            Send(client, "This is a test<EOF>");
            sendDone.WaitOne();

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

            // Write the response to the console.
            SendingMessage(string.Format("Response received : {0}", response));

            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }

    private 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());
            SendingMessage(string.Format("Socket connected to {0}", client.RemoteEndPoint.ToString()));

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

    private 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)
        {
            SendingMessage(e.Message);
        }
    }

    private 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;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            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();
            }
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }

    public 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 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);
            SendingMessage(string.Format("Sent {0} bytes to server.", bytesSent));
            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            SendingMessage(e.Message);
        }
    }
}

-上面有一个clickData的click事件,我想用它来将数据传递到服务器。 我想知道在已连接时调用哪种方法来传递新数据。

您将使用Send方法发送数据。 但是,此示例代码看起来实际上只是为了向您展示这些异步方法中的某些方法。 StartClient方法关闭所有内容,这可能不是您想要执行的操作。 您可能需要编写自己的代码才能执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM