. NET network communication programming [using socket for transmission of strings, files, and serialized objects]-using encapsulated Network Services 4 [chat rooms]

Source: Internet
Author: User

In this case, a simple chat room is written using the encapsulated network service class, and TCP and asynchronous socket technologies are used:

App. config file:

 DemonstrationCode  <? XML version = "1.0" encoding = "UTF-8" ?>  <  Configuration  >      <  Appsettings  >          <! -- Local server name -->          <  Add   Key ="Servername"   Value = "127.0.0.1"  />          <! -- Local port -->          <  Add   Key = "SERVERPORT"   Value = "6001"  />          <! -- Remote server name -->          <  Add   Key ="Remoteservername"   Value = "127.0.0.1"  />          <! -- Remote server port -->          <  Add   Key = "Remoteserverport"   Value = "6002"  />      </  Appsettings  >  </ Configuration  > 

Complete chat form code:

 DEMO code Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. drawing; using system. LINQ; using system. text; using system. windows. forms; using tcplabcommon; using system. net. sockets; using system. net; using system. configuration; using system. threading; using system. io; namespace tcplabchat1 {public partial class frmchat: FORM {delegate void updateviewhandler (netpacket packet); Delegate void updateviewwithmsghandler (string MSG );/// <  Summary  > /// File dialog box ///</  Summary  > Openfiledialog FD = new openfiledialog ();/// <  Summary  > /// TCP service object [provides the packet sending and package receiving functions] and receives messages and files /// </  Summary  > Netpacketservice tcppacketservicesvr = NULL ;/// <  Summary  > /// TCP service object [provides the packet sending and package receiving functions], and sends messages and files ///</  Summary  > Netpacketservice tcppacketserviceclient = NULL ;/// <  Summary  > /// Client socket [send messages and files] /// </  Summary  > Socket clientsocket = NULL ;/// <  Summary  > /// Local server name /// </ Summary  > Public String servername {get {return configurationmanager. receivettings ["servername"] ;}/// <  Summary  > /// Local listening port /// </  Summary  > Public int32 SERVERPORT {get {return convert. toint32 (configurationmanager. configurettings ["SERVERPORT"]) ;}/// <  Summary > /// Name of the Peer server /// </  Summary  > Public String remoteservername {get {return configurationmanager. deleetask[ "remoteservername"] ;}/// <  Summary  > /// The listening port of the other server /// </  Summary  > Public int32 remoteserverport {get {return convert. toint32 (configurationmanager. deleetask[ "remoteserverport"]) ;}} public frmchat () {initializecomponent () ;}private void frmchat_load (Object sender, eventargs e) {receivemessage ();}/// <  Summary  > /// Asynchronously receives messages from the other party /// </  Summary  > Private void receivemessage () {socket serversocket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); endpoint = new ipendpoint (IPaddress. parse (servername), SERVERPORT); // create an endpoint serversocket. BIND (endpoint); // bind the endpoint serversocket. listen (0); // start listening to serversocket. beginaccept (New asynccallback (asynccallbackaccept), serversocket); // receives a request} private void asynccallbackaccept (iasyncresult result) {socket serversocket = (socket) result. asyncstate; socket ctsocket = serversocket. endaccept (result); networkstream netstream = new networkstream (ctsocket); tcppacketservicesvr = new netpackettcpasynservice (netstream); (tcppacketservicesvr as netpackettcpasynservice ). onreceivedpacket + = new tcpasynhandler1 (frmchat_onreceivedpacket); tcppacketservicesvr. extends epacket ();} void frmchat_onreceivedpacket (netpacket packet) {// run the delegate pointing method on the thread in the window interface to avoid cross-thread access to the UI issue invoke (New updateviewhandler (updateview ), packet );}///<  Summary  > /// Update the interface /// </  Summary  > /// <  Param   Name = "Packet"  >  </  Param  > Private void updateview (netpacket packet) {string msglist = txtmsglist. text; Switch (packet. packethead. ptype) {Case packettype. string: msglist + = "\ r \ n:" + packet. data. tostring (); break; Case packettype. binary: netfile F = tcppacketservicesvr. parsefile (byte []) packet. data); msglist + = "\ r \ n received the file sent by the recipient:" + F. filename; filestream FS = NULL; try {string fname = application. startuppath + "\" + F. filename; FS = new filestream (fname, filemode. create); FS. write (F. content, 0, F. content. length); FS. flush ();} catch (exception e) {MessageBox. show (E. message);} finally {FS. close ();} break; Case packettype. complex: break; default: break;} txtmsglist. TEXT = msglist;} private void updateview (string MSG) {string msglist = txtmsglist. text; msglist + = "\ r \ n" + MSG; txtmsglist. TEXT = msglist ;}///<  Summary  > /// Send a message /// </  Summary  > /// <  Param   Name = "Sender"  >  </  Param  > /// < Param   Name = "E"  >  </  Param  > Private void btnsendmsg_click (Object sender, eventargs e) {If (txtmsg. text. trim (). length = 0) return; If (clientsocket = NULL) {clientsocket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); clientsocket. connect (IPaddress. parse (remoteservername), remoteserverport); networkstream netstream = new networkstream (clientsocket); tcppacketserviceclient = new netpackettcpasynservice (netstream);} // register an event, the function executed after successful sending [Note that this event is registered only once] // cancels the subscription event (tcppacketserviceclient as netpackettcpasynservice ). onaftersendpacket-= new tcpasynhandler2 (frmchat_onaftersendpacket); // subscribe to events again (tcppacketserviceclient as netpackettcpasynservice ). onaftersendpacket + = new tcpasynhandler2 (frmchat_onaftersendpacket); // send the packet tcppacketserviceclient. sendtext (txtmsg. text. trim ());}///<  Summary  > /// Function executed after successful sending /// </  Summary  > /// <  Param   Name = "MSG"  >  </  Param  > Void frmchat_onaftersendpacket (netpackethead packethead) {Switch (packethead. ptype) {Case packettype. string: String msglist = txtmsglist. text; msglist + = "\ r \ n:" + txtmsg. text. trim (); txtmsglist. TEXT = msglist; break; Case packettype. binary: // run the delegate pointing method in the thread in the window interface to avoid cross-thread access to the UI issue invoke (New updateviewwithmsghandler (updateview), "I sent the file: "+ new fileinfo (FD. filename ). name); break; Case packettype. complex: break; default: break ;}}/// <  Summary  > /// Send the file ///</  Summary  > /// <  Param   Name = "Sender"  >  </  Param  > /// <  Param   Name = "E"  > </  Param  > Private void btnsendfile_click (Object sender, eventargs e) {If (FD. showdialog () = system. windows. forms. dialogresult. cancel) {return;} If (clientsocket = NULL) {clientsocket = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); clientsocket. connect (IPaddress. parse (remoteservername), remoteserverport); networkstream netstream = new networkstream (clientsocket); tcppacketserviceclient = new netpackettcpasynservice (netstream);} // register an event, the function executed after successful sending [Note that this event is registered only once] // cancels the subscription event (tcppacketserviceclient as netpackettcpasynservice ). onaftersendpacket-= new tcpasynhandler2 (frmchat_onaftersendpacket); // subscribe to events again (tcppacketserviceclient as netpackettcpasynservice ). onaftersendpacket + = new tcpasynhandler2 (frmchat_onaftersendpacket); tcppacketserviceclient. sendfile (FD. filename );}}}

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.