C # Socket generation 2: simple socket communication,

Source: Internet
Author: User
Tags sendmsg

C # Socket generation 2: simple socket communication,

After reading Series 1, we have enabled the listener status for socket tcp. In this chapter, we will explain how to create the socket communication code.

Create a class TSocketBase

1 public abstract class TSocketBase 2 {3 // encapsulate socket 4 internal Socket _ Socket; 5 // callback 6 private AsyncCallback aCallback; 7 // buffer for receiving data 8 private byte [] Buffers; 9 // identify whether 10 private volatile bool IsDispose has been released; 11 // 10 K buffer space 12 private int BufferSize = 10*1024; 13 // receive message Status Code 14 private SocketError ReceiveError; 15 // status code 16 private SocketError SenderError; 17 // The number of bytes received each time 18 private int Receiv ESize = 0; 19 // accept empty messages 20 byte ZeroCount = 0; 21 22 public abstract void Receive (byte [] rbuff); 23 24 public void SetSocket () 25 {26 this. aCallback = new AsyncCallback (this. receiveCallback); 27 this. isDispose = false; 28 this. _ Socket. receiveBufferSize = this. bufferSize; 29 this. _ Socket. sendBufferSize = this. bufferSize; 30 this. buffers = new byte [this. bufferSize]; 31} 32 33 34 // <summary> 35/ // Close and release the resource 36 // </summary> 37 // <param name = "msg"> </param> 38 public void Close (string msg) 39 {40 if (! This. isDispose) 41 {42 this. isDispose = true; 43 try 44 {45 try {this. _ Socket. close () ;}46 catch {}47 IDisposable disposable = this. _ Socket; 48 if (disposable! = Null) {disposable. dispose ();} 49 this. buffers = null; 50 GC. suppressFinalize (this); 51} 52 catch (Exception) {} 53} 54} 55 56 57 // <summary> 58 // recursive message receiving method 59 /// </summary> 60 internal void ReceiveAsync () 61 {62 try 63 {64 if (! This. isDispose & this. _ Socket. connected) 65 {66 this. _ Socket. beginReceive (this. buffers, 0, this. bufferSize, SocketFlags. none, out SenderError, this. aCallback, this); 67 CheckSocketError (ReceiveError); 68} 69} 70 catch (System. net. sockets. socketException) {this. close ("the link has been closed");} 71 catch (System. objectDisposedException) {this. close ("the link has been closed");} 72} 73 74 75 76 // <summary> 77 // receives the message callback function 78 /// </summary> 79 // <param name = "iar"> </param> 80 private void effececallback (IAsyncResult iar) 81 {82 if (! This. IsDispose) 83 {84 try 85 {86 // receive the message 87 ReceiveSize = _ Socket. EndReceive (iar, out ReceiveError); 88 // check the status code 89 if (! CheckSocketError (ReceiveError) & SocketError. success = ReceiveError) 90 {91 // determine the number of accepted bytes 92 if (ReceiveSize> 0) 93 {94 byte [] rbuff = new byte [ReceiveSize]; 95 Array. copy (this. buffers, rbuff, ReceiveSize); 96 this. receive (rbuff); 97 // reset the number of consecutive blank lines received by 98 ZeroCount = 0; 99 // continue receiving the message asynchronously 100 ReceiveAsync (); 101} 102 else103 {104 ZeroCount ++; 105 if (ZeroCount = 5) {this. close ("error link");} 106} 107} 108} 109 Catch (System. net. sockets. socketException) {this. close ("the link has been closed");} 110 catch (System. objectDisposedException) {this. close ("the link has been closed ");} 111} 112} 113 114 // <summary> 115 // error 116 // </summary> 117 // <param name = "socketError"> </ param> 118 // <returns> </returns> 119 bool CheckSocketError (SocketError socketError) 120 {121 switch (socketError) 122 {123 case SocketError. socketError: 124 case Sock EtError. versionNotSupported: 125 case SocketError. tryAgain: 126 case SocketError. protocolFamilyNotSupported: 127 case SocketError. connectionAborted: 128 case SocketError. connectionRefused: 129 case SocketError. connectionReset: 130 case SocketError. disconnecting: 131 case SocketError. hostDown: 132 case SocketError. hostNotFound: 133 case SocketError. hostUnreachable: 134 case SocketError. networkDown: 135 case S OcketError. networkReset: 136 case SocketError. networkUnreachable: 137 case SocketError. noData: 138 case SocketError. operationAborted: 139 case SocketError. shutdown: 140 case SocketError. systemNotReady: 141 case SocketError. tooManyOpenSockets: 142 this. close (socketError. toString (); 143 return true; 144} 145 return false; 146} 147 148 // <summary> 149 // message sending method 150 // </summary> 151 internal int SendMsg (byte [] Buffer) 152 {153 int size = 0; 154 try155 {156 if (! This. isDispose) 157 {158 size = this. _ Socket. send (buffer, 0, buffer. length, SocketFlags. none, out SenderError); 159 CheckSocketError (SenderError); 160} 161} 162 catch (System. objectDisposedException) {this. close ("the link has been closed");} 163 catch (System. net. sockets. socketException) {this. close ("the link has been closed");} 164 buffer = null; 165 return size; 166} 167}

Previously, we had a socket asynchronous message receiving mechanism, and the resource code has been disabled for synchronous message sending.

There are many ways to accept messages provided by the bottom layer of message net. Why should we choose what we have written above? It is designed to be compatible with U3D, silverlight, wpf, wp, wf, and other programs that can be executed.

Create an implementation class TSocketClient

1 public class TSocketClient: TSocketBase 2 {3 /// <summary> 4 /// whether it is a server-side resource 5 /// </summary> 6 bool isServer = false; 7 8 /// <summary> 9 // The client actively requests the Server 10 /// </summary> 11 /// <param name = "ip"> </param> 12 // <param name = "port"> </param> 13 public TSocketClient (string ip = "127.0.0.1 ", int port = 9527) 14 {15 isServer = false; 16 this. _ Socket = new System. net. sockets. socket (AddressFamily. interNetwor K, SocketType. stream, ProtocolType. tcp); 17 this. _ Socket. connect (ip, port); 18 this. setSocket (); 19 this. receiveAsync (); 20} 21 /// <summary> 22 // This indicates that the server receives a valid link for initialization 23 /// </summary> 24 /// <param name = "socket"> </param> 25 public TSocketClient (Socket socket) 26 {27 isServer = true; 28 this. _ Socket = socket; 29 this. setSocket (); 30 this. receiveAsync (); 31} 32 33 // <summary> 34 // 35 after receiving the message /// </summary> 36 /// <Param name = "rbuff"> </param> 37 public override void Receive (byte [] rbuff) 38 {39 Console. writeLine ("Receive Msg:" + System. text. UTF8Encoding. default. getString (rbuff); 40 if (isServer) 41 {42 this. sendMsg (System. text. UTF8Encoding. default. getBytes ("Holle Client! "); 43} 44} 45}

Because it is a test example, I have written the server and client implementation classes, but used them to differentiate between different constructors, whether they are the client or server identifiers.

 

Next, let's test the code.

 1   class Program 2     { 3         static void Main(string[] args) 4         { 5             TCPListener tcp = new TCPListener(); 6             TSocketClient client = new TSocketClient(); 7             client.SendMsg(System.Text.UTF8Encoding.Default.GetBytes("Holle Server!")); 8             Console.ReadLine(); 9         }10     }

 

The running result shows that the connection is successful and the message is sent successfully.

 

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.