/// <summary> /// 链接服务器回调 /// </summary> /// <param name="async"></param> public void SocketCallback(IAsyncResult async) { //强转对象 Socket socket = (Socket)async.AsyncState; try { //获取Socket套接字信息 socket.EndConnect(async); if (SocketHeartbeat(socket)) { socket.BeginReceive(reception, 0, reception.Length, SocketFlags.None, new AsyncCallback(SocketReceive), socket);//异步接收数据 Sockets.Add(socket); ComboBox.BeginInvoke((EventHandler) delegate { ComboBox.Items.Add(IPEnd.Address + " " + IPEnd.Port.ToString()); ComboBox.SelectedIndex = ComboBox.Items.Count - 1; }); RichTextcontrol($"成功链接服务器IP:{socket.RemoteEndPoint}\r\n"); } } catch (Exception e) { RichTextcontrol($"链接服务器:ip {IPEnd.Address} {IPEnd.Port} 失败!! 原因是:{e.Message}\r\n "); } }
/// <summary> /// 创建Udp对象 /// </summary> public void Socket_Udp() { UdpClientLoad = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); UdpClientLoad.Bind(IPEnd); ComboBox.BeginInvoke((EventHandler) delegate { ComboBox.Items.Add(IPEnd.Address + IPEnd.Port.ToString()); ComboBox.SelectedIndex = ComboBox.Items.Count - 1; }); EndPoint endPoint = IPEnd; UdpClientLoad.BeginReceiveFrom(reception, 0, reception.Length, SocketFlags.None, ref endPoint, SocketReceive, UdpClientLoad); }
/// <summary> /// 回调获取Socket客户端对象 /// </summary> /// <param name="async"></param> private void Socketcall_back(IAsyncResult async) { //强制对象 Socket socket = (Socket)async.AsyncState; try { if (socketload == null) { return; } //获取Socket客户端对象 Socket Socketclient = socket.EndAccept(async); if (SocketHeartbeat(Socketclient)) { Socketclient.BeginReceive(reception, 0, reception.Length, SocketFlags.None, new AsyncCallback(SocketRend), Socketclient);//异步接收数据 Sockets.Add(Socketclient); ComboBox.BeginInvoke((EventHandler) delegate { ComboBox.Items.Add(Socketclient.RemoteEndPoint); ComboBox.SelectedIndex = ComboBox.Items.Count - 1; }); RichTextcontrol($"有客户端接入:{Socketclient.RemoteEndPoint}\r\n"); } } catch { if (socketload == null) { return; } } finally { //继续回调监听客户端 socket.BeginAccept(new AsyncCallback(Socketcall_back), socket); } }