{"id":30665341,"url":"https://github.com/code-artist/codearteng.tcp","last_synced_at":"2025-08-31T20:21:19.331Z","repository":{"id":57982335,"uuid":"80533711","full_name":"Code-Artist/CodeArtEng.Tcp","owner":"Code-Artist","description":"Tcp Server and Client Implementation with multiple client handling.","archived":false,"fork":false,"pushed_at":"2025-07-13T04:44:02.000Z","size":1388,"stargazers_count":12,"open_issues_count":0,"forks_count":5,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-08-13T14:40:57.050Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Code-Artist.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-31T15:35:47.000Z","updated_at":"2025-07-13T04:44:06.000Z","dependencies_parsed_at":"2022-08-29T08:11:43.519Z","dependency_job_id":null,"html_url":"https://github.com/Code-Artist/CodeArtEng.Tcp","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/Code-Artist/CodeArtEng.Tcp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Artist%2FCodeArtEng.Tcp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Artist%2FCodeArtEng.Tcp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Artist%2FCodeArtEng.Tcp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Artist%2FCodeArtEng.Tcp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Code-Artist","download_url":"https://codeload.github.com/Code-Artist/CodeArtEng.Tcp/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Code-Artist%2FCodeArtEng.Tcp/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273032938,"owners_count":25034069,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-31T02:00:09.071Z","response_time":79,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-08-31T20:21:14.711Z","updated_at":"2025-08-31T20:21:19.321Z","avatar_url":"https://github.com/Code-Artist.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CodeArtEng.Tcp\n## Introduction\n\u003cb\u003eCodeArtEng.Tcp\u003c/b\u003e is a .NET Tcp Server and Client implementation with multiple client handling written in C#.![NuGet](https://img.shields.io/nuget/v/CodeArtEng.Tcp)\u003cbr\u003e\n\u003cb\u003eCodeArtEng.Tcp.WinForms\u003c/b\u003e contains user controls for WinForms application. ![NuGet](https://img.shields.io/nuget/v/CodeArtEng.Tcp.WinForms)\u003cbr\u003e\n\n### Components\n- [TcpServer](#TCP-Server): TCP Server with multiple clients handling capability\n- [TcpClient](#TCP-Client): TCP Client with connection and incoming data monitoring.\n- [TcpAppServer](#TCP-Application-Server): TCP Application Server for application automation.\n- [TcpAppServerPlugin](#TCP-Application-Server-Plugin): Multi Instance Plugin for TCP Application Server.\n- TcpAppServerWindows: Derived from TcpAppServer. TCP Application Server for WinForms.\n- [TCP Application Client](#TCP-Application-Client): TCP Application Client for application automation.\n\n### About TCP Application Protocol\nTCP Application Protocol is created as high level communication protocol to provide a common remote interface between applications which can be easily integrated to any application with minimum coding effort from developer on both server and client application.\n\n## TCP Server\n### Features\n- Multi-threaded TCP server with multi client support.\n- Message Receive Mode: Delimiter / Timeout.\n\n### Quick Start\n```C#\nprivate TCPServer Server;\nprivate void Init()\n{\n    Server = new TcpServer(\"MyTcpServer\"); //Create TCP Server\n    Server.ServerStarted += Server_StateChanged; //Subscribe to Server Events\n    Server.ServerStopped += Server_StateChanged;\n    //Optional event: client connecting, before perform max client check\n    Server.IncomingConnection += Server_IncomingConnection;     \n    //Optional event: Review and decide if client can be accept.\n    Server.ClientConnecting = Server_ClientConnecting;     \n    //Require: Handle new connected client.\n    Server.ClientConnected += Server_ClientConnected;\n\n    //Configure how MessageReceived event should trigger\n    // A) Delimiter character mode (DEFAULT)\n    Server.MessageReceivedEndMode = TcpServerMessageEndMode.Delimiter;\n    Server.MessageDelimiter = Convert.ToByte('\\n');\n\n    // OR\n    // B) Trigger by timeout between read cycle.\n\n    Server.MessageReceivedEndMode = TcpServerMessageEndMode.Timeout;\n    Server.InterMessageTimeout = 100; //Timeout 100ms\n}\n\nprivate void Server_ClientConnected(object sender, TcpServerEventArgs e)\n{\n    //Subscribe to TCPServerConnection bytes received event to capture incoming byte\n    // this event trigger as soon as any byte received ignore message receive end mode.\n    e.Client.BytesReceived += Client_BytesReceived;\n\n    //**************** OR ****************\n\n    //Subscribe to either TCPServerConnection message received event or\n    //ProcessReceivedMessageCallback callback to process received message string / bytes\n    \n    //a) Message Received event\n    e.Client.MessageReceived += Client_MessageReceived;   \n    \n    //b) ProcessReceivedMessageCallback callback\n    e.Client.ProcessReceivedMessageCallback = ProcessMessage;    \n}\n\nprivate void ProcessMessage(TcpServerConnection client, string message, byte[] messageBytes)\n{\n    //Process inocming message here.\n}\n\nprivate void Client_BytesReceived(object sender, BytesReceivedEventArgs e)\n{\n    byte [] data = e.Client.ReceivedBytes; //Retrieve read content from Client\n\n    //Handle incoming data from TCP Client.\n\n    e.Client.WriteToClient(\"Message to Client.\"); //Write to Client\n    ...\n  }\n\nprivate void Client_MessageReceived(object sender, MessageReceivedEventArgs e)\n{\n    string message = e.ReceivedMessage; //Handle incoming message string from TCP Client.\n    ...\n}\n```\n### Disposing and Clean up\nIncoming connection monitoring handle by thread.\nWe recommend to always call the `Dispose()` method to properly terminate thread for unused object. Failing to do may resulting application keep running in background even forms are closed.\n\n## TCP Client\n### Features\n- Read / Write bytes array / string to Server.\n- Check connection status with Server.\n- Data receive by event.\n\n### Quick Start\n```C#\nprivate TCPClient Client;\nprivate void Init()\n{\n    Client.HostName = \"127.0.0.1\";\n    Client.Port = 10000;\n    //Notify when connection to server break.\n    Client.ConnectionStatusChanged += Client_ConnectionStatusChanged;\n    Client.DataReceived += Client_DataReceived; //Subscribe to data received event.\n    Clinet.Connect();   //Connect to Server.\n}\n\nprivate void Client_DataReceived(object sender, EventArgs e)\n{\n    String inputMsg = e.GetString(); //Read input from TCP Server as String\n    byte [] inputData = e.Data;      //Read input from TCP Server as byte array\n\n    //Process incoming data or message ...\n}\n\nprivate void WriteDataToServer()\n{\n    //Example\n    Client.Write(\"String message to Server.\");  \n    Client.WriteLine(\"Message terminated with LF.\");\n    Client.Write(new byte[]{'D','a','t','a'}); //Write to Server in byte array\n    ...\n}\n```\nTo read message from TCP Server without using DataReceived event, skip DataReceived event subscription and use one of the following method to read input from TCP Server.\n```C#\n    byte[] inputData = ReadBytes();  //Read input as byte array.\n    string inputString = ReadString(); //Read input as string.\n```\n\n### Disposing and Clean up\nBoth connection status and incoming data monitoring handle by thread.\nWe recommend to always call the `Dispose()` method to properly terminate thread for unused object. Failing to do may resulting application keep running in background even forms are closed.\n\n## TCP Application Protocol\n### Introduction\nTCP Application Protocol is a high level communication protocol created on top of TCP (Transmission Control Protocol)  served as common remote interface between applications which can be easily integrated to any application with minimum coding effort from developer on both server and client application. With TCP application, serial port instrument can be accessible by multiple applications.\n\nWith TCP Application Protocol, application specific commands can be easily defined by server application. Each registered command keyword can include with  one or more optional or mandatory parameter as needed. Incoming message from client will be verify against registered command set and have defined parameters parse and assigned. Developer can focus on implementation of each of the command.\n\n### About TCP Application Protocol\nTCP Application Protocol is a text based protocol, where any TCP client including [RealTerm](https://realterm.sourceforge.io/) can be use to interact TCP Application Server. TCP Application message format is defined as follow:\n\n1. Command sent from client start with command keyword follow by parameters if any and terminated with carriage return (\\r, 0x0D). Extra parameters in commands will be ignored.\u003cbr\u003e\n`\u003cCommand Keyword\u003e [Parameter0] ... [ParameterN]`\n\n2. Response from server to client is begin with status (`OK` or `ERR`) following by response message.\u003cbr/\u003e\n`\u003cStatus\u003e \u003cResponse Message / Return Value\u003e`\n\n![TCP Application Class Diagram](\u003cDoc/CodeArtEng.Tcp_UML.png\u003e)\n\n- TcpAppServer - TCP Application Server. Host for remote control.\n- ITcpAppServerPlugin - TCP Application Server Plugin Interface.\n- TcpAppServerPlugin - TCP Application Server Plugin Helper Class for plugin implementation.\n- TcpAppCommand - TCP Application Registered Command.\n- TcpAppParameter - TCP Application Command Parameter.\n- TcpAppInputCommand - TCP Application Server Received Command.\n- TcpAppClient - TCP Application Client. Remove control client.\n\n### Implement TCP Application Client from Terminal\n`TcpAppClient` is not the only way to communicate with `TcpAppServer` based application, it can be done with any ordinary TCP Client with few additional steps.\n\n1. Connect to Server using any TCP Client terminal such as **RealTerm** and etc.\n2. TCP Client: Sent `SignIn [ConnectionID]` to Server. `ConnectionID` is optional, can be either computer name or any unique name represent current instance. If duplicated ID exists, an unique ID will be returned.\n3. Execute other commands using format as described above.\n\n**Auto SignIn - Configure from TcpAppServer**\nIf `ConnectionID` from client is not cruicial for your application, you may consider to set `AutoSignInClient` in `TcpAppServer` class to `true` where incoming client connection will be automatically signed in on first non-system command.\n\n## TCP Application Server\n### Quick start\n```C#\nprivate TcpAppServer AppServer;\n\nprivate void SetupServer()\n{\n    // \u003c------\n    AppServer = new TcpAppServer();  //Create instance using Generic TCP Application Server Class\n    // OR\n    AppServer = new TcpAppServerWindows(this); //Create instance using TCP Application Server for WinForms\n    // ------\u003e\n\n    //Setup Server\n    AppServer.WelcomeMessage = \"Welcome to TCP Application Server\";\n    AppServer.MaxClients = 5; //Define number of clients allowed to connects\n    AppServer.ExecutionTimeout = 1000;\n    AppServer.ClientConnected += AppServer_ClientConnected; //\n    AppServer.ClientDisconnected += AppServer_ClientDisconnected;\n    AppServer.ClientSignedIn += AppServer_ClientSignedIn;\n    AppServer.ClientSigningOut += AppServer_ClientSigningOut;\n\n    RegisterAppServerCommands();\n    RegisterPlugins();\n    AppServer.Start(12000);   //Start Server\n}\n\nprivate void AppServer_ClientConnected(object sender, TcpServerEventArgs e)\n{\n    //Get information of connected client. We can decide if want to accept this incoming connection.\n    string ipAddress = e.Client.ClientIPAddress;\n    string port = e.Client.Port;\n\n    //To reject client Connection\n    e.Client.Close(); return;\n\n    //(Optional) subscribe to client object event to monitor incoming messages\n    e.Client.MessageReceived += Client_MessageReceived;\n    e.Client.BytesSent += Client_MessageSent;\n}\n\nprivate void RegisterPlugins()\n{\n    //Two options available. Either register plugin using type\n    AppServer.RegisterPluginType(typeof(TcpAppServerSamplePlugin));\n\n    // OR discover and register all plugin class which implemented ITcpAppServerPlugin\n    AppServer.Registerplugins();\n}\n\nprivate void RegisterAppServerCommand()\n{\n    //Register application specific commands to TCP Application Server.\n    //Command can have 0 or more mandatory and/or optional parameters.\n    AppServer.RegisterCommand(\"CustomFunction\", \"Dummy Custom Function\", custonFunctionCallback,\n        TcpAppParameter.CreateParameter(\"P1\", \"Parameter P1\"),          //Add mandatory parameter\n        TcpAppParameter.CreateOptionalParameter(\"P2\", \"Parameter P2\")); //Add optional parameter\n}\n\nprivate void customFunctionCallback(TcpAppInputCommand sender)\n{\n    //Client information is accessible using sender.AppClient object\n    string clientIP = sender.AppClient.Connection.ClientIPAddress;\n\n    //Implement function actions...\n\n    sender.Status = TcpAppcommandStatus.OK;  //Default status is ERR. Update when execution success.\n    sender.OutputMessage = \"Execution Completed.\";\n}\n```\n\n### Disposing and Clean up\nSimilar to `TcpServer`, it is recommended to call `Dispose()` method to properly terminate all threads for unused object.\nFailing to do may resulting application keep running in background even forms are closed.\n\n## Working with Plugin\nTCP Application Server Plugin provide great capability to application where new feature and components can be added at later stage. TCP Application Protocol equipped with capability to handle and extend command set in plugin components as well as instantiate objects in server application, let’s see how.\n\n### TCP Application Server Plugin\n```C#\n//Example plugin implemetation\npublic class TcpAppServerSamplePlugin : ITcpAppServerPlugin\n{\n    //Plugin class must implement ITcpAppServerPlugin interface\n    //TcpAppPlugin in helper class contains common implementation for plugin object.\n    private readonly TcpAppServerPlugin TcpAppPlugin;\n\n    public string PluginName { get; } = \"Sample Plugin\";\n    public string PluginDescription { get; } = \"Long description about this plugin...\";\n    public string Alias { get; set; } //Plugin instance name, set by TcpAppServer\n\n    public TcpAppServerSamplePlugin()\n    {\n        TcpAppPlugin = new TcpAppServerPlugin();\n\n        //Register commands.\n        TcpAppPlugin.RegisterCommand(\"PluginCommand1\", \"Plugin Command 1\", delegate (TcpAppInputCommand sender)\n            {\n                sender.Status = TcpAppCommandStatus.OK;\n                sender.OutputMessage = \"Command 1 Executed!\";\n            });\n\n    }\n\n    public bool DisposeRequest() { return true; }\n\n    //Make sure the following methods ShowHelp and ExecutePluginCommand execute from TcpAppServerPlugin\n    public void ShowHelp(TcpAppInputCommand sender){ TcpAppPlugin.ShowHelp(sender); }\n    public void ExecutePluginCommand(TcpAppInputCommand sender){ TcpAppPlugin.ExecutePluginCommand(sender); }\n}\n```\n\n## TCP Application Client\nTCP Application Client helper class. Communication with TCP Application Server can be done with any TCP client as well.\n\n### Quick Start\n```C#\nprivate TcpAppClient AppClient;\n\npublic void SetupClient()\n{\n    AppClient = new TcpAppClient();\n    AppClient.ConnectionStatusChanged += Client_ConnectionStatusChanged;\n    AppClient.ResponseReceived += Client_ResponseReceived;\n    AppClient.CommandSend += Client_CommandSend;\n}\n\nprivate void ConnectToServer()\n{\n    AppClient.HostName = \u003cServer IP\u003e;\n    AppClient.Port = \u003cServer Port\u003e;\n    AppClient.Connect(); //Connect to TCP Application Server to retrieve commands and plugin objects list.\n\n    //List of commands and plugin objects are accessible from the following properties.\n    List\u003cstring\u003e commands = AppClient.Commands;\n    List\u003cstring\u003e plugins = AppClient.PluginObjects;\n}\n\nprivate void ExecuteCommand()\n{\n    //Send command to Server\n    TcpAppCommandResult result = AppClient.ExecuteCommand(\u003cCommand\u003e, 2000); //Execute command, timeout in 2 seconds.\n\n    //Process returned result...\n}\n```\n\n\n### TCP Application Client Terminal\n\u003cb\u003eTCPAppClientTerminal\u003c/b\u003e is an example of TCP client implementation.\u003cbr\u003e\nThis application implemented generic terminal where user can enter the commands manually to interact with server application.\n\n![TcpAppClientTerminal](\u003cDoc/TCPAppTerminal.png\u003e)\n\nCode Artist 2017 - 2022\nwww.codearteng.com\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcode-artist%2Fcodearteng.tcp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcode-artist%2Fcodearteng.tcp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcode-artist%2Fcodearteng.tcp/lists"}