服务器端代码
public static NetManager server;
private async void IniServer(int port)
{
EventBasedNetListener listener = new EventBasedNetListener();
server = new NetManager(listener);
var re = server.Start(port);
MessageText += $"{re}";
//订阅各个处理事件
listener.PeerConnectedEvent += Listener_PeerConnectedEvent;
listener.NetworkReceiveEvent += Listener_NetworkReceiveEvent;
listener.PeerDisconnectedEvent += Listener_PeerDisconnectedEvent;
listener.ConnectionRequestEvent += Listener_ConnectionRequestEvent;
while (true)
{
server.PollEvents();
await Task.Delay(1);
}
}
服务器接收客户端连接请求
private void Listener_ConnectionRequestEvent(ConnectionRequest request)
{
MessageText += "\r\n客户端连接:"+request.RemoteEndPoint.Address+":"+request.RemoteEndPoint.Port;
request.Accept();//接受连接请求
}
客户端:
public static NetManager client;
private async void IniServer(int port)
{
if (client!=null&&client.IsRunning)
return;
EventBasedNetListener listener = new EventBasedNetListener();
client = new NetManager(listener);
var re = client.Start(port);
client.Connect("127.0.0.1", 5888, "key");//发送连接请求
while (true)
{
client.PollEvents();
await Task.Delay(5);
}
}
连接之后使用peer发送数据:
private void ButtonDisSend_Click(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
int i = 0;
while (true)
{
if (client.ConnectedPeerList.Count < 1) break;
NetDataWriter writer = new NetDataWriter();
writer.Put("发送了一些数据0123"+i);
client.ConnectedPeerList[0].Send(writer, DeliveryMethod.ReliableOrdered);
i++;
Thread.Sleep(100);
}
});
}
服务器Listener_NetworkReceiveEvent事件将接收到数据。