In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to use the C# open source library SimpleTCP, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Brief introduction
When you need to implement a TCP client or server at work, it will be troublesome and boring to write it yourself every time, and it's too big to use the SuperSocket library. At this point, you can use SimpleTCP, which is of course limited to the C # language.
SimpleTCP is a simple and useful .NET library that handles the repetitive task of launching and using TCP sockets (client and server), which is easy to use and has little code. Its interior is not the direct use of Socket, but re-encapsulated on the basis of TcpClient, and the interface is simpler and clearer.
Its main features are as follows:
The source code is simple: there are only several classes in the source code, and each class is not big. You can understand it without comments on the basis of understanding the usage of TcpClient.
Single function: unlike other libraries, it only focuses on the implementation of simple TCP client, server, and does not have to worry about increasing the complexity of the system.
Easy to use: the following example will explain in detail that it takes only a few lines of code to start a client or server, and it's easy to extend the functionality.
Tell me about its shortcomings (which seem to me to be perfectly acceptable):
The update has been stopped: the last update time is 2017, but the function of the library is relatively simple, single, and there are not so many updates.
Performance is not optimal: the underlying layer is based on TcpClient, and performance is destined not to be too high, but it can be used wherever you can use TcpClient.
Usage
You can reference SimpleTCP.dll directly in the project, and the dll file can be installed through NuGet or downloaded from github.
There is a special character splitting protocol within SimpleTCP that can be used directly, or you can implement your own protocol in DataReceived event handlers.
Implement the client
The code to implement a client is as follows:
/ / initialize var client = new SimpleTcpClient (); / / set the encoding format. Default is UTF8client.StringEncoder = System.Text.ASCIIEncoding.ASCII;// set delimiter, default is 0x13client.Delimiter = Encoding.ASCII.GetBytes ("\ r") [0]; / / event client.DelimiterDataReceived + = (sender, msg) = > {Console.WriteLine ("DelimiterStr-" + DateTime.Now.ToString () + msg.MessageString);} / / for events that receive data, you can implement your own protocol client.DataReceived + = (sender, msg) = > {/ / byte array Console.WriteLine ("Data:" + BitConverter.ToString (msg.Data)); / / string message Console.WriteLine ("ReceivedStr:"+ msg.MessageString);}
DelimiterDataReceived and DataReceived use two different byte linked lists internally, which do not affect each other when parsed. Try not to do time-consuming operations in the handlers of these two events, otherwise it will affect the subsequent data reception.
SimpleTCP has no heartbeat, reconnect capabilities, and no properties to feedback the client connection status (the connection status of the internal TcpClient is not recommended). We can extend these functions directly, as follows:
Bool exit = false;bool connected = false;Task.Factory.StartNew (() = > {while (! exit) {try {if (connected) {/ / send heartbeat client.Write ("); Task.Delay (10000) .Wait () } else {/ / disconnected reconnect client.Connect ("127.0.0.1", 4196); connected = true; Task.Delay (1000). Wait ();}} catch (Exception) {connected = false Client.Disconnect ();}, TaskCreationOptions.LongRunning)
Copy the above code in order to the Main function in the console, and then add the following code to send and receive data:
While (true) {string strLine = Console.ReadLine (); if (strLine = = "esc") {exit = true; client.Disconnect (); return } if (connected) {/ / get the reply message from the server. Wait up to 3 seconds. When you receive the message, you can return it in advance / / you can also use Write and WriteLine methods to send data. WriteLine will automatically add the delimiter var replyMsg = client.WriteLineAndGetReply (strLine, TimeSpan.FromSeconds (3)). If (replyMsg! = null) {Console.WriteLine (replyMsg);}
Note: WriteLineAndGetReply uses DataReceived internally and does not automatically remove delimiters.
Implement the server side
The function of the server is relatively simple. The received split data is processed and returned to the client. The code is as follows:
/ / initialize var server = new SimpleTcpServer (); / / set the encoding format. Default is UTF8server.StringEncoder = System.Text.ASCIIEncoding.ASCII;server.Delimiter = Encoding.ASCII.GetBytes ("\ r") [0]; / / split data reception event server.DelimiterDataReceived + = (sender, msg) = > {Console.WriteLine (msg.TcpClient.Client.RemoteEndPoint.ToString () + ":" + msg.MessageString); msg.ReplyLine ("Reply-" + msg.MessageString);} / / data receiving data server.DataReceived + = (sender, msg) = > {Console.WriteLine (msg.TcpClient.Client.RemoteEndPoint.ToString () + ":" + msg.MessageString);}; / / client connection event server.ClientConnected + = (sender, msg) = > {Console.WriteLine ("ClientConnected:" + msg.Client.RemoteEndPoint.ToString ());} / / client disconnect event server.ClientDisconnected + = (sender, msg) = > {Console.WriteLine ("ClientDisconnected:" + msg.Client.RemoteEndPoint.ToString ());}; / / start listening to server.Start (4196); / / listening IPvar listeningIps = server.GetListeningIPs (); / / listening V4Ipvar listeningV4Ips = server.GetListeningIPs (). Where (ip = > ip.AddressFamily = = System.Net.Sockets.AddressFamily.InterNetwork) Task.Factory.StartNew () = > {while (true) {/ / number of connections Monitoring int clientsConnected = server.ConnectedClientsCount; Console.WriteLine ("number of clients currently connected:" + clientsConnected); Task.Delay (10000). Wait ();}}, TaskCreationOptions.LongRunning); Console.ReadLine (); / / stop snooping server.Stop (); Console.WriteLine ("stop server!") ; Console.ReadLine (); these are all the contents of the article "how to use the C# open source library SimpleTCP". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.