我们如何使用C#从一个Windows项目向另一个Windows项目中发送简单数据(例如“ mango”)-异步进行?
这是客户端代码。
public partial class MainWindow : Window
{
private Socket _clientSocket;
private byte[] _buffer;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback,
3333), new AsyncCallback(ConnectCallback), null);
}
private void ConnectCallback(IAsyncResult AR)
{
_clientSocket.EndConnect(AR);
}
private void SendCallback(IAsyncResult AR)
{
_clientSocket.EndSend(AR);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
Click("MANGO");
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
Click("GRAPES");
}
public void Click(string xmlstring)
{
try
{
byte[] xmlbuffer = Encoding.ASCII.GetBytes(xmlstring);
_clientSocket.BeginSend(xmlbuffer, 0, xmlbuffer.Length,
SocketFlags.None, new AsyncCallback(SendCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
服务器代码是
public partial class Server : Window
{
private Socket _serversocket, _clientSocket;
private byte[] _buffer;
public Server()
{
InitializeComponent();
StartServer();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void StartServer()
{
_serversocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_serversocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
_serversocket.Listen(0);
_serversocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void AcceptCallback(IAsyncResult AR)
{
_clientSocket = _serversocket.EndAccept(AR);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length,
SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
_serversocket.BeginAccept(new AsyncCallback(AcceptCallback),
null);
}
private void ReceiveCallback(IAsyncResult AR)
{
int received = _clientSocket.EndReceive(AR);
Array.Resize(ref _buffer, received);
string text = Encoding.ASCII.GetString(_buffer); // here get ans
Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize);
}
}
当我单击button1时,“ mango”一词应该出现在服务器端。当我单击button2时,“ grapes”一词应该出现在服务器端。
当我第一次单击button1时,它将起作用,并且在服务器端显示“ mango”。但是第二次单击button2时,什么也没发生-“ grapes”一词并没有出现在服务器端。
请帮助纠正它。
答案 0 :(得分:0)
尝试在_clientSocket.BeginReceive
末尾致电ReceiveCallback
。