C # communication programming

Source: Internet
Author: User

Http://topic.csdn.net/u/20080623/08/4bbd2475-45f1-42e3-a613-16b094759ade.html? 75578

Socket communication:

C # code

Public class xmlsocket {// asynchronous socket diagnostics // incoming data from client. public static string data = NULL from the client; // thread signal. the thread initializes a new instance of the manualresetevent class with a Boolean value indicating whether to set the initial status to terminated. Public static manualresetevent alldone = new manualresetevent (false); // static void main (string [] ARGs) // {// startlistening (); //} public static void startlistening () {// data buffer for incoming data. incoming data buffer byte [] bytes = new byte [1024]; // establish the local endpoint for the socket. create a local port // The DNS name of the computer // running the listener is "host.contoso.com ". IPaddress; string ipstring = configurationmanager. appsettings. get ("socketip"); If (ipstring = NULL | ipstring = string. empty) {iphostentry iphostinfo = DNS. gethostentry (DNS. gethostname (); IPaddress = iphostinfo. addresslist [0];} else {IPaddress = IPaddress. parse (ipstring);} int port; string portstring = configurationmanager. appsettings. get ("socketport"); If (portstring = NULL | portstring = string. empty) {Port = 11001;} else {Port = int. parse (portstring);} ipendpoint localendpoint = new ipendpoint (IPaddress, Port); // create a TCP/IP socket. socket listener = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); // bind the socket to the local endpoint and listen for incoming connections. bind the port and data try {listener. BIND (localendpoint); listener. listen (100); While (true) {// set the event to nonsignaled state. set the event alldone with no signal. reset (); // start an asynchronous socket to listen for connections. restart the asynchronous connection listener. beginaccept (New asynccallback (acceptcallback), listener); // wait until a connection is made before continuing. continue alldone after the connection is created. waitone () ;}} catch (exception e) {//} public static void acceptcallback (iasyncresult AR) {try {// signal the main thread to continue. accept the callback method. This section applies this method to the main application. Program The thread sends a signal, // let it continue to process and establish a connection with the client alldone. set (); // get the socket that handles the client request. obtain the client request handle socket listener = (socket) ar. asyncstate; socket handler = listener. endaccept (AR); // create the State object. stateobject state = new stateobject (); State. worksocket = handler; handler. beginreceive (state. buffer, 0, stateobject. buffersize, 0, new asynccallback (readcallback), State);} catch (Ti On E) {// }}/// <summary> // The same as the callback method, the read callback method is also an asynccallback delegate. /// This method reads one or more bytes from the client socket into the data buffer, and then calls the beginreceive method again until the data sent by the client is complete. /// After reading the entire message from the client, the console displays the string and closes the server socket that processes the connection with the client. /// </Summary> /// <Param name = "Ar"> iasyncresult DeleGate </param> Public static void readcallback (iasyncresult AR) {try {string content = string. empty; // retrieve the State object and the handler socket create a custom State object from the asynchronous State object. stateobject state = (stateobject) ar. asyncstate; socket handler = state. worksocket; // processing handle // read data from the client socket. read int bytesread = handler. endreceive (AR); If (bytesread> 0) {// business Code String result = dosomething (...); string Len = encoding. utf8.getbytes (result ). length. tostring (). padleft (8, '0'); log. writeline (LEN); send (LEN + result, Handler) ;}} catch (exception e) {//} Private Static void send (string data, socket handler) {try {// convert the string data to byte data using utf8 encoding. byte [] bytedata = encoding. utf8.getbytes (data); // begin sending the data to the remote device. handler. beginsend (bytedata, 0, bytedata. length, 0, new asynccallback (sendcallback), Handler);} catch (exception E) {// }}/// <summary> /// send /// </Summary> /// <Param name = "Ar"> </param> Private Static void sendcallback (iasyncresult AR) {try {// retrieve the socket from the State object. socket handler = (socket) ar. asyncstate; // complete sending the data to the remote device. int bytessent = handler. endsend (AR); stateobject state = new stateobject (); State. worksocket = handler; handler. beginreceive (state. buffer, 0, stateobject. buffersize, 0, new asynccallback (readcallback), State); handler. shutdown (socketshutdown. both); handler. close ();} catch (exception e) {//} public static void stoplistening () {alldone. close (); log. close ();} /// <summary> /// method for processing the specific business /// </Summary> /// <returns> </returns> Private Static string dosomething (int I) {// specific business code, returns the string information to be returned.} // <summary> // log Writing Method // </Summary> // <Param name = "strlog"> write content </Param> Public static void writelog (string strlog) {// write Log Code }}

/// Thread execution body, forward the message /// </Summary> /// <Param name = "OBJ"> the user name passed to the thread execution body, used to communicate with users </param> private void threadfunc (Object OBJ) {// obtain the current user socket clientskt = _ transmit_tb [OBJ] As socket through the forwarding table; // The main loop while (true) {try {// receives the first packet. // Because the program logic structure is simple, the first packet content sent by the client is judged one by one here. // The implementation here is not elegant enough, but it is a solution to this simple model. Byte [] packetbuff = new byte [_ maxpacket]; clientskt. receive (packetbuff); string _ STR = encoding. unicode. getstring (packetbuff ). trimend ('\ 0'); // if it is a message sent to an offline friend if (_ Str. startswith ("cmd: friendmessage") {string username = _ Str. substring ("cmd: friendmessage ". length, 20 ). trim (); string messages = _ Str. substring ("cmd: friendmessage ". length + 20, _ Str. length-"cmd: friendmessage ". length-20); savemess Age (OBJ as string, username, messages); continue;} // if it is an offline request if (_ Str. startswith ("cmd: requestlogout") {_ transmit_tb.remove (OBJ); updatefriendlist (string) OBJ, false, ""); // string svrlog = string. format ("[system message] user {0} has been disconnected at {1... current online users: {2} \ r \ n ", OBJ, datetime. now, _ transmit_tb.count); // console. writeline (svrlog); // send system messages to all clients // foreach (dictionaryentry de in _ transmit_tb) // {// stri Ng _ clientname = de. key as string; // socket _ clientskt = de. value as socket; // _ clientskt. send (encoding. unicode. getbytes (svrlog); //} thread. currentthread. abort ();} // if it is a friend list request if (_ Str. startswith ("cmd: requestfriendlist") {serializefriendlist (OBJ, clientskt ); // send the offline user information to the user's able tabmessage = readmessage (OBJ as string); If (tabmessage! = NULL) {foreach (datarow myrow in tabmessage. rows) {If (myrow ["sendusername"]. tostring () = "system: Message") {clientskt. send (encoding. unicode. getbytes (myrow ["message"]. tostring ();} else {clientskt. send (encoding. unicode. getbytes ("cmd: friendmessage" + myrow ["sendusername"]. tostring (). padright (20, '') + myrow [" message "]. tostring () ;}}// you do not need to accept the next packet. The current loop body exists. Continue;} // if it is a list of requesting friends/If (_ Str. startswith ("cmd: requestonlinelist") // {// byte [] onlinebuff = serializeonlinelist (); // first send a response signal, user client judgment // clientskt. send (encoding. unicode. getbytes ("cmd: requestonlinelist"); // clientskt. send (onlinebuff); // you do not need to accept the next packet and exit the current loop body. // Continue; // find the user if (_ Str. startswith ("find: findfriend") {datatable tabfind = tabuser. clone (); datarow [] findrow = NULL; string username = _ Str. substring ("find: findfriend ". length, _ Str. length-"find: findfriend ". length); If (username. equals ("find: whoonline") {// you can check who is online. findrow = tabuser. select ("zx = 1");} else // exact search {findrow = tabuser. select ("username = '" + username + "'");} forea CH (datarow myrow in findrow) {tabfind. importrow (myrow);} clientskt. send (encoding. unicode. getbytes ("find: findfriend"); iformatter format = new binaryformatter (); memorystream stream = new memorystream (); format. serialize (stream, tabfind); stream. position = 0; byte [] ret = new byte [_ maxpacket]; int COUNT = 0; Count = stream. read (Ret, 0, _ maxpacket); While (count> 0) {clientskt. send (RET); count = Stream. read (Ret, 0, _ maxpacket);} clientskt. send (encoding. unicode. getbytes ("find: findfriendend"); stream. close (); tabfind = NULL; findrow = NULL; // you do not need to accept the next packet and exit the current loop body. Continue;} // request to add a friend if (_ Str. startswith ("find: addfriendask") {string username = _ Str. substring ("find: addfriendask ". length, _ Str. length-"find: addfriendask ". length); // query the receiver's socket through the forwarding table if (_ transmit_tb.count! = 0 & _ transmit_tb.containskey (username) {socket receiverskt = _ transmit_tb [username] As socket; receiverskt. send (encoding. unicode. getbytes ("find: addfriendask" + OBJ as string);} // you do not need to accept the next packet. The current loop body exists. Continue;} // reply to promise to add a friend if (_ Str. startswith ("find: addfriendyes") {string username = _ Str. substring ("find: addfriendyes ". length, _ Str. length-"find: addfriendyes ". length); // Save the data datatable tabmyfriend = new datatable (); // Save the user tabmyfriend. readxml (mypath + "\ userfriend \" + OBJ as string + ". XML "); datarow newrow = tabmyfriend. newrow (); newrow ["username"] = username; tabmyfriend. rows. add (newrow); tabmyfriend. writexml (mypath + "\ userfriend \" + OBJ as string + ". XML ", xmlwritemode. writeschema, false); // save its friend tabmyfriend = new datatable (); tabmyfriend. readxml (mypath + "\ userfriend \" + username + ". XML "); datarow newrow1 = tabmyfriend. newrow (); newrow1 ["username"] = OBJ as string; tabmyfriend. rows. add (newrow1); tabmyfriend. writexml (mypath + "\ userfriend \" + username + ". XML ", xmlwritemode. writeschema, false); tabmyfriend = NULL; serializefriendlist (OBJ, clientskt );
Related Article

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: info-contact@alibabacloud.com 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.