C # Socket network communication asynchronous processing SocketAsyncEventArgs,
C # Socket network communication asynchronous processing of SocketAsyncEventArgs asynchronous Socket operations
1. Simple server implementation:
Public partial class Form_Server: Form {private Socket socket; public Form_Server () {InitializeComponent ();} private void Form_Server_Load (object sender, EventArgs e) {try {// obtain the local IP address IPAddress ipaddress = Dns. getHostByName (Dns. getHostName ()). addressList [0]; txt_ip.Text = ipaddress. toString ();} catch (Exception ex) {MessageBox. show (ex. message) ;}}// enable Socket listening private void btn_listent_open _ Click (object sender, EventArgs e) {try {if (string. isNullOrEmpty (txt_ip.Text) {MessageBox. show ("Enter ip Address");} // enable the listener IPAddress ip = IPAddress. parse (txt_ip.Text); IPEndPoint localEP = new IPEndPoint (ip, Int32.Parse (txt_port.Text); socket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); socket. bind (localEP); socket. listen (1000); // AcceptAsync asynchronous SocketAsyncEventAr Gs socketAsyncEventArgs = new SocketAsyncEventArgs (); socketAsyncEventArgs. completed + = new EventHandler <SocketAsyncEventArgs> (socketAsyncEventArgs_Completed_AcceptAsync); socketAsyncEventArgs. remoteEndPoint = localEP; socketAsyncEventArgs. userToken = socket; socket. acceptAsync (socketAsyncEventArgs); // The message prompts this. lb_msg.Items.Add ("[server]:"); this. lb_msg.Items.Add ("listener succeeded");} catch (Exception ex) {M EssageBox. show (ex. message) ;}}// start an asynchronous operation to accept an incoming connection attempt void socketAsyncEventArgs_Completed_AcceptAsync (object ServerSocket, SocketAsyncEventArgs e) {// disabled, overlapped operations are aborted if (e. socketError = SocketError. operationAborted) {// The operation is closed, and the overlapping operation is aborted. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[server end]:"); this. lb_msg.Items.Add ("socketAsyncEventArgs_Completed_AcceptAsync: Disabled, overlapping operations aborted> SocketError: Disabled AtionAborted ") ;}); return ;}// this connection is reset by a remote peer if (e. socketError = SocketError. connectionReset & e. bytesTransferred = 0) {// this connection is reset by a remote peer. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[server end]:"); this. lb_msg.Items.Add ("socketAsyncEventArgs_Completed_AcceptAsync: This connection is reset by a remote peer computer> SocketError: ConnectionReset") ;}); return ;}if (e. lastOperation = SocketAsyncOperation. accept) {try {Socket acceptSocket = e. acceptSocket; // start an asynchronous request to access the connected System. net. sockets. the Socket object receives data SocketAsyncEventArgs socketAsyncEventArgsReceiveAsync = new SocketAsyncEventArgs (); socketAsyncEventArgsReceiveAsync. userToken = acceptSocket; byte [] receiveBuff = new byte [1024*4]; socketAsyncEventArgsReceiveAsync. setBuffer (receiveBuff, 0, receiveBuff. length); socketAsyncEventArgsReceiveAsync. completed + = n Ew EventHandler <SocketAsyncEventArgs> (socketAsyncEventArgs_Completed_ReceiveAsync); acceptSocket. receiveAsync (socketAsyncEventArgsReceiveAsync); // The message prompts this. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[client]:"); this. lb_msg.Items.Add ("connection successful") ;}) ;}catch (Exception ex) {MessageBox. show (ex. message);} // start an asynchronous operation to accept an incoming connection attempt. Recursive e. acceptSocket = null; socket. acceptAsync (e) ;}// starts an asynchronous Request from the connected System. net. sockets. the received data in the Socket object is void socketAsyncEventArgs_Completed_ReceiveAsync (object acceptSocket, SocketAsyncEventArgs e) {// disabled, and overlapping operations are aborted if (e. socketError = SocketError. operationAborted) {// The operation is closed, and the overlapping operation is aborted. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[server end]:"); this. lb_msg.Items.Add ("socketAsyncEventArgs_Completed_ReceiveAsync: Disabled, overlapping operations aborted> SocketError: OperationAbort Ed ") ;})); return ;}// this connection is reset by a remote peer if (e. socketError = SocketError. connectionReset & e. bytesTransferred = 0) {// this connection is reset by a remote peer. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[server end]:"); this. lb_msg.Items.Add ("socketAsyncEventArgs_Completed_ReceiveAsync: This connection is reset by a remote peer computer> SocketError: ConnectionReset") ;}); return ;}if (e. socketError = SocketError. success & e. buffer. length> 0) {tr Y {Socket socket = acceptSocket as Socket; string ipAddress = socket. remoteEndPoint. toString (); int lengthuffer = e. bytesTransferred; byte [] receiveBuffer = e. buffer; byte [] buffer = new byte [lengthuffer]; Buffer. blockCopy (receiveBuffer, 0, buffer, 0, lengthuffer); string message = Encoding. UTF8.GetString (buffer); this. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[client]:"); this. lb_msg. Items. add ("" + message) ;}); socket. send (Encoding. UTF8.GetBytes (string. format ("received message {0 }:{ 1}", DateTime. now. toString ("yyyy/MM/dd HH: mm: ss"), message); socket. receiveAsync (e);} catch (Exception ex) {MessageBox. show (ex. message) ;}}// disable Socket listening private void btn_listent_Close_Click (object sender, EventArgs e) {try {if (socket! = Null) {socket. close ();} this. lb_msg.Items.Add ("[server]:"); this. lb_msg.Items.Add ("listener disabled successfully");} catch (Exception ex) {MessageBox. show (ex. message );}}}
2. Simple client implementation:
Public partial class ClientMainForm: Form {private Socket _ socket; public ClientMainForm () {InitializeComponent () ;}// log on to private void btn_login_Click (object sender, EventArgs e) {try {IPAddress ip = IPAddress.Parse(this.txt _ ip. text); IPEndPoint ipendPoint = new IPEndPoint (ip, Int32.Parse(this.txt _ port. text); _ socket = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp ); _ Socket. connect (ipendPoint); this. lb_msg.Items.Add ("[client]:"); this. lb_msg.Items.Add ("successfully connected to the server"); // enable SocketAsyncEventArgs socketAsyncEventArgs (); // set the message buffer size byte [] receiveBuff = new byte [1024*4]; socketAsyncEventArgs. setBuffer (receiveBuff, 0, receiveBuff. length); socketAsyncEventArgs. userToken = _ socket; // bind the callback event socketAsyncEventArgs. completed + = sock EtAsyncEventArgs_Completed_ReceiveAsync; _ socket. receiveAsync (socketAsyncEventArgs);} catch (Exception ex) {MessageBox. show (ex. message) ;}} // start an asynchronous request to start from the connected System. net. sockets. receive data in the Socket object. Void socketAsyncEventArgs_Completed_ReceiveAsync (object sender, SocketAsyncEventArgs e) {// disabled. Overlapping operations are aborted if (e. socketError = SocketError. operationAborted) {this. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[client]:"); this. lb_msg.Items.Add ("socketAsyncEventArgs_Completed_ReceiveAsync: Disabled, overlapping operations aborted: OperationAborted") ;}); return ;}// this connection is reset by a remote peer if (e. socketError = SocketError. connectionReset & e. bytesTransferred = 0) {// this connection is reset by a remote peer. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[client]:"); this. lb_msg.Items.Add ("socketAsyncEventArgs_Completed_ReceiveAsync: This connection is reset by a remote peer COMPUTER: ConnectionReset") ;}); return ;} Socket socket = sender as Socket; if (e. socketError = SocketError. success & e. buffer. length> 0) {string ipAddress = socket. remoteEndPoint. toString (); int lengthuffer = e. bytesTransferred; byte [] receiveBuffer = e. buffer; byte [] buffer = new byte [lengthuffer]; Buffer. blockCopy (receiveBuffer, 0, buffer, 0, lengthuffer); string message = Encoding. UTF8.GetString (buffer); this. lb_msg.Invoke (new Action () => {this. lb_msg.Items.Add ("[service user]:"); this. lb_msg.Items.Add ("" + message) ;}); socket. receiveAsync (e) ;}} // send the message private void btn_sendmsg_Click (object sender, EventArgs e) {if (string. isNullOrEmpty (txt_msg.Text) {MessageBox. show ("enter message");} else {_ socket. send (System. text. encoding. UTF8.GetBytes (txt_msg.Text ));}}}