It's very easy to write, and I think it's very interesting.
Program
Main code
Public classMessage {Form1 mainfrom=NULL; PublicMessage () {} PublicMessage (Form1 form) {Mainfrom=form; } Public BOOLStartreceive (intPort) { Try{IPEndPoint IEP=NewIPEndPoint (Ipaddress.loopback, Port); Socket TCPServer=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Tcpserver.bind (IEP); Tcpserver.listen ( -); Tcpserver.beginaccept (NewAsyncCallback (Accept), tcpserver); return true; } Catch(Exception ex) {return false; } } Private voidAccept (IAsyncResult ia) {socket Socket= ia. AsyncState asSocket; varClient =socket. Endaccept (IA); byte[] buf =New byte[1024x768]; Socket. BeginAccept (NewAsyncCallback (Accept), socket); StateObject State=NewStateObject (); State.worksocket=client; Try{client. BeginReceive (State.buffer,0, Stateobject.buffersize, Socketflags.none,NewAsyncCallback (Receive), state); } Catch(Exception ex) {//Console.WriteLine ("Error listening on request: \ r \ n" + ex.) ToString ()); } } Private voidReceive (IAsyncResult ia) {stateobject State= ia. AsyncState asStateObject; if(state = =NULL) { return; } Socket Client=State.worksocket; if(Client = =NULL) { return; } Try { intCount =client. EndReceive (IA); if(Count >0) { Try{client. BeginReceive (State.buffer,0, Stateobject.buffersize, Socketflags.none,NewAsyncCallback (Receive), client); stringContext = Encoding.GetEncoding ("gb2312"). GetString (State.buffer,0, Count); //Show Receive MessageMainfrom. Loginformtextchange (context); } Catch(Exception ex) {//Console.WriteLine ("Error receiving data: \r\n{0}", ex. ToString ()); } } } Catch(Exception err) {}} Public voidSendMessage (intPortstringm) {System.Text.Encoding CharSet= System.Text.Encoding.GetEncoding ("gb2312"); Socket tcpClient=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Try{tcpclient.connect (ipaddress.loopback, Port); stringsendmsg =m; byte[] Buff =charset.getbytes (sendmsg); Tcpclient.send (buff, buff. Length,0); } Catch(SocketException e) {}}} Public classStateObject {//Client socket. PublicSocket Worksocket =NULL; //Size of receive buffer. Public Const intBufferSize =1024x768; //Receive buffer. Public byte[] buffer =New byte[buffersize]; //Received data string. PublicStringBuilder SB =NewStringBuilder (); }
SOURCE Http://yun.baidu.com/s/1i39XtjR
Communication of two programs using sockets