日期:2014-05-17 浏览次数:21118 次
public class StateObject
{
//服务器端
public Socket udpServer = null;
//接受数据缓冲区
public byte[] buffer = new byte[10*1024];
//远程终端
public EndPoint remoteEP;
public bool flag = false;
}
private void ServerForm_Load(object sender, EventArgs e)
{
StartServer startServer = new StartServer();
thread = new Thread(new ThreadStart(startServer.ServerBind));
thread.Start();
}
public void ServerBind()
{
//主机IP
IPEndPoint serverIp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8686);
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpServer.Bind(serverIp);
IPEndPoint clientIp = new IPEndPoint(IPAddress.Any, 0);
state = new StateObject();
state.udpServer = udpServer;
state.remoteEP = (EndPoint)clientIp;
AsynRecive();
}
#endregion
#region 异步接受消息
public void AsynRecive()
{
lock (state)
{
state.udpServer.BeginReceiveFrom(state.buffer, 0, state.buffer.Length, SocketFlags.None, ref state.remoteEP,
new AsyncCallback(ReciveCallback), null);
receiveDone.WaitOne();
}
&n