我正在研究使用异步客户端-服务器套接字的 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);
}
}
}
-- 上面有一个 buttonData 的点击事件,我想用它来将数据传递给服务器。我想知道在已经连接时调用哪种方法来传递新数据。