Socketasynceventargs socket echo server

Source: Internet
Author: User
Namespace microshaoft {using system; using system. text; using system. net; using system. net. sockets; using system. servicemodel. channels; Class echoserver {socket server; Public echoserver (ipendpoint localpoint) {Server = new socket (localpoint. addressfamily, sockettype. stream, protocoltype. TCP); server. BIND (localpoint); server. listen (5); accept_async ();} private void accept_async () {var acce PT = new socketasynceventargs (); accept. completed + = accept_completed; server. acceptasync (accept);} int I = 0; void accept_completed (Object sender, socketasynceventargs e) {accept_async (); var client = E. acceptsocket; E. usertoken = I ++; E. completed-= accept_completed; E. completed + = receive_completed; var buffer = new byte [1024]; E. setbuffer (buffer, 0, buffer. length); client. receiveasync (E );} Void receive_completed (Object sender, socketasynceventargs e) {var client = sender as socket; If (E. bytestransferred = 0) {console. writeline ("socket is closed"); client. close ();} else {// client. send (E. buffer, E. bytestransferred, socketflags. none); byte [] buffer = new byte [E. bytestransferred]; buffer. blockcopy (E. buffer, 0, buffer, 0, buffer. length); string S = bitconverter. tostring (buffer );/ /S = encoding. ASCII. getstring (buffer); console. writeline ("==={ 0} usertoken: [{1}] {0} bytes transferred: [{2}] {0} data: [{3}] {0 }=== "," \ r \ n ", E. usertoken, E. bytestransferred, S); // console. writeline (s); client. receiveasync (e) ;}}} namespace consoleapplication {using system; using system. net; using microshaoft; // <summary> /// Summary of class1. /// </Summary> public class class1 {// <summary> // ApplicationProgram . /// </Summary> // [stathread] Static void main (string [] ARGs) {// todo: add Code To start the application // IPaddress IPA; IPaddress. tryparse ("", out IPA); echoserver x = new echoserver (New ipendpoint (IPA, 8180); console. writeline ("Hello World"); console. writeline (environment. version. tostring (); console. readline ();}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.