Giter Club home page Giter Club logo

simpletcp's Introduction

SimpleTCP

Straightforward and incredibly useful .NET library to handle the repetitive tasks of spinning up and working with TCP sockets (client and server).

NuGet Package: https://www.nuget.org/packages/SimpleTCP/

Build Status

Want a TCP server that listens on port 8910 on all the IP addresses on the machine?

var server = new SimpleTcpServer().Start(8910);

Want a TCP client that connects to 127.0.0.1 on port 8910?

var client = new SimpleTcpClient().Connect("127.0.0.1", 8910);

Want to send "Hello world!" to the server and get the reply that it sends within 3 seconds?

var replyMsg = client.WriteLineAndGetReply("Hello world!", TimeSpan.FromSeconds(3));

Want to receive a message event on the server each time you see a newline \n (char 13), and echo back any messages that come in?

server.Delimiter = 0x13;
server.DelimiterDataReceived += (sender, msg) => {
                msg.ReplyLine("You said: " + msg.MessageString);
            };

Want to know how many clients are connected to the server?

int clientsConnected = server.ConnectedClientsCount;

Want to change the text encoding that the client and server uses when sending and receiving strings? (The default is ASCII/UTF8.)

server.StringEncoder = System.Text.ASCIIEncoding.ASCII;
client.StringEncoder = System.Text.ASCIIEncoding.ASCII;

Want to get the IP addresses that the server is listening on?

var listeningIps = server.GetListeningIPs();

Want to get only the IPv4 addresses the server is listening on?

var listeningV4Ips = server.GetListeningIPs().Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);

Want to make your node.js friends stop saying things like "with node I can spin up a web server in only 4 lines of code"?

var server = new SimpleTcpServer().Start(80);
server.DataReceived += (sender, msg) => {
                msg.Reply("Content-Type: text/plain\n\nHello from my web server!"); 
                };

(But really, this library isn't ideal for web server-ing, so don't do that in prod.)

simpletcp's People

Contributors

aquamoth avatar brandonpotter avatar brudo avatar manuel-s avatar oceanairdrop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simpletcp's Issues

Is their a limit on how many clients can connect to this server? cause some clients can't connect.

Hi, I have used this library in my IoT project in which the devices send the data to the server, the server application is running on windows server 2012. I can see all the devices which are connected to this server. Sometimes I have noticed when 20 devices are connected, other devices can't connect I have even tried to connect from my computer but it doesn't connect until I restart server application. This is becoming a big problem for me cause I am connecting more devices to the server and devices can't connect because of connection timeout.
-Thanks

GetConnectedClientsCount keeps slowly increasing forever

I am using SimpleTcp for a GPRS server application. Basically, we have about 200 GPS trackers installed in vehicles throughout the country, and they transmit their coordinates to my SimpleTcp app via GPRS (i.e. via the cellular network) every 10 - 60 seconds for most vehicles (and every hour for some). Everything is working nicely, however, everytime I call "GetConnectedClientsCount", the count keeps increasing. I.e. it starts off on around 200 (so one connection for each vehicle) but over time it increases - after a day it's at about 10,000! Is this normal? Is SimpleTCP opening a new connection every time it receives data from a vehicle? I don't think so, otherwise the ConnectedClientsCount would increase much quicker. But for some reson, it's creating about 10 new connections every minute. Any ideas?

can't check if connection to server is still establshed

may it would be got to have an option to check whether the connection is establish or not

can use - TcpClient.Connected for that and return that via a separate getter

example which fit to my needs:

public bool Connected { get { return (_client != null) ? _client.Connected: false; } }

Question: how to run only server as windows service

Hallo , i have a question and hope someone can help me with.
Im new in TCP/IP , but not new in windows services. How do i run server class in window services?
Windows Service run at timer / dispatcher timer , but i think it is not that simple run server class as service. Idea is, check for packages on client periodically.

server.datareceived can't get the client who sent it

Hello

I'm trying to develop a small server/client chat with multiple rooms for a school project.

However for a certain reason, i need to know which client(simpletcpclient) sent the data in this thingy:

srv.DataReceived += (sender, msg) =>
            {  
                    list.addclient(sender);
            }

So something like this code above, however the sender is returning as a SimpleTcpServer, i'm stuck and i'd apreciate if someone could lend me a hand here. Thanks for your time

resolved

Calling TcpClient.Close() prevents subsequent DataReceived events for other clients

There are several points in my application where the server needs to disconnect a client. For some reason, calling TcpClient.Close() in an event handler prevents the DataReceived event from being invoked when other clients send data.

Below is a sample that demonstrates this issue:

var server = new SimpleTcpServer();

server.DataReceived += (s, a) =>
{
    Console.WriteLine("Data");
    a.TcpClient.Close();
};

server.ClientConnected += (s, a) =>
{
    Console.WriteLine("Connected");
};

server.Start(8088);

Console.ReadLine();
server.Stop();

Using the code above and an application like PacketSender to test, I expect that a connection would be closed each time data is sent to the server. Instead, the first client to connect to the server is disconnected after data is sent and subsequent connections never raise the DataReceived event.

Getting the IP and Port of client

Excuse me for the naive(?) question, i have little to no experience in c#. In the DataRecieved function, is there a way for the server to get the ip and the port of the sender object? Or any other way?

Thanks in advance!

Feature Request: Broadcasting

When I was using this library I was really missing a Broadcast/Receive pair of methods on the server and client respectively.

Other than that, it is really nice to use.

Problems in installing SimpleTCP

Hello to everybody,

I am trying to install simpletcp package (https://www.nuget.org/packages/SimpleTCP/1.0.24) in my ShaprDevelop IDE but I get the following error message:

Install-Package : Could not install package 'SimpleTCP 1.0.24'. You are trying to install t
his package into a project that targets '.NETFramework,Version=v4.0', but the package does
not contain any assembly references or content files that are compatible with that framewor
k. For more information, contact the package author.

Both in manually installing (from the console prompt or directly form 'mamaging package' menu)

I have the lastest .NET framework (4.6.2) installed.

Could somenone help me ?

Advanced thanks

Namespace not available in Unity.

Hi,

I've compiled to DLL and imported into Unity, but the SimpleTCP namespace isn't available so i can't access any of the SimpleTCP library.

Is there something special i need to do to make this work with Unity?

Multi-byte delimiter support

Had a situation the other day where XML messages were coming across a TCP connection.

Thought it would be nice to be able to specify a multi-byte delimiter to split messages, for example '/whatever>' could be the end of a message.

Adding an issue so I don't forget the next time I have a few hours to implement or if someone else wants to take a shot at it.

Missing license

This project has no license, so theoretically / strictly legally nobody is allowed to use it, except to study the code and fork it here on github (but then you can't do anything with the fork). Even contributors can't use the library since they all share exclusive copyright for the code and should always ask permission from all other contributors before using the code in any way.

More details: https://choosealicense.com/no-license/

If not for "real" production use, the library is still quite useful for prototyping, unit testing and stuff like that, but in my company I wouldn't be allowed to use it even for this (due to strict regulatory requirements in my specific branch - medical software development - every library has to be checked and validated before it can be used and this includes the license).

SimpleTcpClient.WriteAndGetReply?

I've been using this framework for a while for simple TCP communications (thanks a lot for making our life easy), but I've reached a point where I need to send a message and listen for the reply synchronously. I've tested with SimpleTcpClient method WriteLineAndGetReply but the problem is that this method inserts a trailing line end char at the end of the string I'm sending, and the thid party system which I'm sending messages to does not support it. Is there any way to remove the final char? Something like WriteAndGetReply?

Thanks.

Edit: (early sending) I've been testing the implementation by copying the code for the method WriteLineAndGetReply and replacing the WriteLine(data) with Write(data). If you see it interesting I may fork the repository and send a pull request with the method WriteAndGetReply.

Add option to listen on 0.0.0.0 instead of individually on all interfaces

I am suggesting to add an option to bind 0.0.0.0 to listen on all interfaces in SimpleTcpServer, instead of itemizing the interfaces and listening on each one individually. This would work well on Windows but might not be supported on all platforms, e.g. Linux, so you may need to make this configurable through an optional parameter, or have the check which OS at run time, or have it try 0.0.0.0 and fall back to individual interfaces if that fails. Thoughts?

Default delimiter 0x13 should be 0x0D ?

Hi, I love this ! Very helpful.
Maybe I'm wrong, but I believe the default delimiter should be 0x0D(or 0x0A if going with newline \n as mentioned in the example). Either way, not a big deal just stumped me at first ;)
This rocks thanks!
-TD

strong-name related error

Hello,

I have used SimpleTCP in my code. When I am trying to implement it, I get the following error:

Could not load file or assembly 'SimpleTCP, Version=1.0.24.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)

"!!" character end of every message ?

If i send text "Hey" to the server i'm getting response like "You said: Hey�". Why it's adding extra character to it ? I can't parse that text to.

I set server.Delimiter to 0x0A but nothing changed.

txtStatus.Text += e.MessageString.Split('!')[0]; // It's not working it's still responding with "!".

Am i doing something wrong ? Thanks!

Here some info for !! chracter :
https://apps.timwhitlock.info/unicode/inspect?s=%13

Getting all connected clients

I decided to use SimpleTcp for a little game I'm developing, and it works prety well. However, I cannot get all connected clients to my server (reviewing the code it seems they are stored in a private list), so... Am I missing anything? Or is there a reason to make them non accessable? Excuse my english and thanks for your work.

[Usage Help] - Event DelimiterDataReceived keep alive?

Hi,

Thank's for this nice library.

I'm confronted to usage problem. I setup a new instance of SimpleTcp in my client library. When DelimiterDataReceived is reached a second time, nothing happens... it's seem my client is disconnected.

To be sure the second data is never send to the server i try to throw a new Exception error but... the exception never appear...

Format of Server protocol (Yes my client can send data like he want...):
[1 char flag][0x00]

Here is the code into the client:

Session session = new Session("127.0.0.1", 4321);
session.Connect();
session.Account.Logon("AccountTest", "TestPassword");

Here is my library (simplified as possible):

using SimpleTCP;

namespace ClientLibrary
{
    public class Session
    {
        // Network
        private string address;
        private int port;
        internal SimpleTcpClient client;
		
	// Core
        public Account Account;
        private PacketManager packetManager;
        internal bool isConnected = false;
		
		
	public Session(string address, int port)
        {
            this.address = address;
            this.port = port;

            client = new SimpleTcpClient
            {
                Delimiter = 0x00
            };
            client.DelimiterDataReceived += Client_DelimiterDataReceived;

            Account = new Account(this);
            packetManager = new PacketManager(this);
        }
		
	private void Client_DelimiterDataReceived(object sender, Message packet)
        {
            packetManager.Process(packet.MessageString);
        }
		
	public void Connect()
        {
            client.Connect(address, port);
        }	
    }
	
    public class Account
    {
        private Session session;

        public Account(Session session)
        {
            this.session = session;
        }

        public void Logon(string account, string password)
        {
            if (session.isConnected)
	        session.client.WriteLine(account + '|' + password);
	}
    }
	
    public class PacketManager
    {
        private Session session;

        public PacketManager(Session session)
        {
            this.session = session;
        }

        public void Process(string data)
        {
	    string flag = data[0];
			
	    switch (flag)
            {
                case 'A':  // Received from Server "Hello"
		{
		    session.isConnected = true;
		    break;
		}
                // this case is never reached
		case 'B': // Received from Server "Ok, it's your credentials"
		{
                    session.Send("Yeah I received your message! But it's a dream...");
		    throw new Exception("This exception never appear");
		    break;
		}
	    }
        }
    }
}

Here is log of the server:

DEBUG : Server : Client connected : 127.0.0.1
DEBUG : Server : Sended -> 'A'
DEBUG : Server : Received from Client -> "AccountTest|TestPassword"
DEBUG : Server : Sended -> 'B'
DEBUG : Server : Client disconnected : 127.0.0.1


Ok I don't know if is it a bug in your library or a pebcak problem, so... if you can help me I thank you a lot in advance, but if not you can close this issue, I would try again and again to performe a good library, thanksfully to your!

Cant use SimpleTCP with Windows Form

Hi,
I tried to write a simple application using Windows Form (VS2015)
I got a TypeLoadSystem exception. Find below the complete message (in French)
Can you help?
Thnak you

Une exception non gérée du type 'System.TypeLoadException' s'est produite dans System.Windows.Forms.dll
Informations supplémentaires : Impossible de charger le type 'SimpleTCP.SimpleTcpServer' à partir de l'assembly 'SimpleTCP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

.NET 3.5 Winform support?

I am not able to install Nuget because my project is in old .net 3.5 framework which can't be upgrade. Do you suggest any ways to use SimpleTCP with 3.5 based project?

TcpClient in Message Class

Hi,

i need access to the TcpClient in the DataReceived event. Is ist possible to add a public member to the Message Class?

Server send message to client

Hi, how the server can send a message to a specific client ?
I can use Broadcast but is not good.

Do you have a solution ?

Message.Reply adding bytes at the end

Quick question. If I send a TCP message from computer A to computer B (which has the SimpleTCP app), and then on computer B, I reply to this message as follows:

message.Reply("12345");

I've realized that if I wait longer than about 450 milliseconds after receiving the data to reply, the reply does not make it through to the originator. I'm using Packet Sender to send and receive TCP data on Computer A. It appears like there are always two replies to the message sent from Computer A. However, only if Computer B replies within about 450 ms will this message make it back to computer A.

Any ideas?

Test to determine network class in RankIpAddress is not comprehensive and could be removed

I see an issue in the code for RankIpAddress, where it seems to embed some arbitrary choices which bump up the priority for certain private IP addresses, one example from each class, but not to other IP addresses that belong to the same class.

As far as I can tell this is only used to sort the list of current connected clients, and for that matter the order the clients are returned in probably doesn't matter in most cases, so the impact appears to be small.

Maybe this is an attempt to get non-Internet clients listed ahead of Internet clients for some reason, although I'm not sure why. The test could be made more complete by checking the full ranges, e.g. 192.168.0.0 - 192.168.255.255, 172.16.0.0 - 172.31.255.255, also checking 127.0.0.1, etc. (and what about IPv6?), it could also be appropriate to remove the ranking code altogether, or just sort them lexically if you want them returned in a consistent order.

For my case, our connected clients do not come from any of the special network prefixes that were selected, so they are currently all the same rank as far as we're concerned. Doesn't seem to cause any harm.

broadcasting

Hy,

server.Broadcast(msg); does not broadcast to all the clients only for the current one.

File Transfer

My goal is a client to transfer a file to the server. Which method can I do this? I want this file reaching the server to be distributed to all connected clients. Is there a method I can transfer files on the client and server part?

memory leak if dont use Delimiter

in SimpleTcpClient

_queuedMsg would not get Clear() if none of the msg go with a delimiter

here in this while loop:

while (c.Available > 0 && c.Connected)
{
byte[] nextByte = new byte[1];
c.Client.Receive(nextByte, 0, 1, SocketFlags.None);
bytesReceived.AddRange(nextByte);
if (nextByte[0] == delimiter)
{
byte[] msg = _queuedMsg.ToArray();
_queuedMsg.Clear();
NotifyDelimiterMessageRx(c, msg);
}
else
{
_queuedMsg.AddRange(nextByte);
}
}

if i dont offer a delimiter in my reply, then _queuedMsg will always run AddRange and never get a Clear().

TCPIP over the internet

Hello. I know that this is not a real issue but don´t know where should i message you. I want to use SimpleTCP for handling servers in my game. Does this api work over the internet? I know it works in local networks but does it work in two different networks without hamichi? Thanks in advance

Closing Client does not remove from Current Clients Connected

I want a limit on amount of clients being able to connect..best way of doing this on the server on the connected event i have a check for client count and if its more than what I want I call disconnect on the client passed into the event to immediately disconnect...but after that (even though my client fails to send any messages and exits) the server connected client count doesn't go down

Maybe add an option on the server for client limit?

ClientDisconnected event is not thrown

The ClientDisconnected Event is not raised at the host.

I have used some differnt TCP Clients to connect to a simple host impementation.
I didn't get any Information about the Client disconnect.

Here is the code I have written.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using SimpleTCP;

namespace SimpleHost
{
    public class Host: IDisposable  
    {
        private const int SERVER_PORT = 1100;
        private const string EOT_MARK = "\n\r";

        private SimpleTcpServer _tcpHost = new SimpleTcpServer();
        private TcpClient _connectedClient = null;

        public Host()
        {
            _tcpHost.ClientConnected += _tcpHost_OnClientConnected;
            _tcpHost.ClientDisconnected += _tcpHost_OnClientDisconnected;
            _tcpHost.DataReceived += _tcpHost_OnDataReceived;
            _tcpHost.AutoTrimStrings = true;
            StartListening();
        }

        private void _tcpHost_OnDataReceived(object sender, Message e)
        {
            Console.WriteLine("Server received: {0}", e.MessageString);

            e.Reply("Echo\n\r");

        }

        private void _tcpHost_OnClientDisconnected(object sender, TcpClient e)
        {
            Console.WriteLine("Client {0} disconnected", e.Client.RemoteEndPoint.ToString());
            if (_connectedClient == e)
            {
                _connectedClient.Dispose();
                _connectedClient = null;
            }

        }

        private void _tcpHost_OnClientConnected(object sender, TcpClient e)
        {
            Console.WriteLine("Client {0} connected", e.Client.RemoteEndPoint.ToString());
            if (_connectedClient == null)
            {
                _connectedClient = e;
            }
            else
            {
                e.Dispose();
            }

        }

        private void StartListening()
        {

            _tcpHost.Start(SERVER_PORT);
        }

        public void Dispose()
        {
            if (_connectedClient !=null)
            {
                _connectedClient.Dispose();
            }
            _tcpHost.Stop();
            _tcpHost = null;
        }
    }
}

server.GetIPAddresses() not working correctly

I want to send messages to clients connected to the server. But the GetIpAdresses method gives me my own ip address or my local address (127.0.0.1).

SimpleTcpClient client;
private void button1_Click(object sender, EventArgs e)
{
foreach (var serverIp in server.GetIPAddresses())
{
client = new SimpleTcpClient();
client.StringEncoder = Encoding.UTF8;
client.DataReceived += Client_DataReceived;
client.Connect(serverIp.ToString(),23);
client.WriteLineAndGetReply(rtb_server_message.Text, TimeSpan.FromSeconds(10));
}

    }

Message Framing

First off, I really appreciate the simplicity of this project. Thanks for sharing it with us.

I quickly got client and server working well sending byte data with Write() and DataReceived(). Am I correct in assuming that Delimiter is currently the only option available for assembling the packets and Length prefixing is not implemented?

After reading this article it seems to me I need to be concerned with the DataReceived event returning partial byte data due to having been split into many packets and network lag. However in my testing after sending a large byte array which was broken into many packets that took ~20 seconds, the byte array returned fully in one DataReceived event. What am I missing here?

Project .Net 4.0 Version

I really appreciate the effort made for the development of this project, which has really made things easier.

I noticed the project was built against .Net Framework 4.6, in which it will be much more better, if a of a lower targeted framework of .Net Framework 4.0 can be released, in order for it to cover a wider range, and not be limited to a specific framework version.

I'll really appreciate, if that can be done, so as to also use it in one of my software in the market, and give credits to this project.

Thanks once more.

OPPS FIXED...
Kindly Close...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.