using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; using System.Windows.Forms;
namespace SocketClient { /// <summary> /// C#网络Socket的数据发送与接收处理(利用异步)的模板(模式) /// </summary> class test_Socket { Socket m_Socket; /// <summary> /// C#网络Socket的数据发送与接收处理(利用异步) /// </summary> /// <param name="_ip">要连接的IP</param> /// <param name="_Port">对方开放的端口</param> public void Net_Socket_Send_Receive(string _ip,int _Port) { IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(_ip), _Port); m_Socket=new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); Byte[] buffer = new Byte[1024]; m_Socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnSend), null); byte[] recvBytes = new byte[20]; m_Socket.BeginReceive(recvBytes, 0, recvBytes.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
} private void OnSend(IAsyncResult ar) { try { m_Socket.EndSend(ar); } catch (ObjectDisposedException) { } catch (Exception ex) { MessageBox.Show(ex.Message, "Send: ", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void OnReceive(IAsyncResult ar) { try { m_Socket.EndReceive(ar);
} catch (ObjectDisposedException) { } catch (Exception ex) { MessageBox.Show(ex.Message, "Receive: ", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
|
请发表评论