Killing TCP Client Threads of TCP Server in C# - c#

i have a TCP server software. I open a thread for every TCP client. (This is not important why i open a thread for every TCP client.) I want to kick a TCP client any time and want to kill its thread. How can i find the thread of TCP client that i want to kick out of server?
Thank you.

You need to keep track of all TcpClient's in existence. For example, use a list to store them. That way you have access to them.

Related

How to manage large number of TCP connections using ASP.NET and C#

I have an application which connects to a third party server let’s call it Server-A. I have been given four different ports i.e.
4000, 40001, 40002, 40003. On each port I can create 20 connections so I can create 80 total connections with server-A. I want to create a service layer that should communicate with server-A on mentioned ports. The technology will be asp.net C#.
The problem statement
1- Application should be non-blocking/asynchronous to entertain 10 to 20 million request per day
2- Whenever the service layer starts it create 20 connections on each port. (Total 80 connections)
2- All connections should remain connected/alive 24/7 and reconnect whenever any connections drops/disconnects. It will send a heartbeat message in idle time.
My Questions
How can I manage these connection? Should I add those to a static list one by one when a TCP socket is successful?
How can I know that a certain connection is dropped/disconnected?
How can I send certain requests on different ports? Let’s say if a>b send it on port 4000 else if a<=b send it on 4001
How can I make it asynchronous?
For an initial start I created a single TCP connection on single port and it works as expected. Then I replicated the same code for other port, but I know it is very bad approach and I have to copy same code 80 times to make 80 connections. I want a clean and scalable way to achieve it, so that in future may be I increase the connection to 100 or more.
Is there any framework which I can use?
Any help would be greatly appraised.
#Kartoos Khan, i have made some services with those requirements and using asynchronous methods is the best way to create high performance services in C#, because:
It does not block IO peripherals, as can be sockets.
Minimize the threads and improve the performance to it.
Let me recommend you the book Writing High-Performance .NET Code. The chapter 4, Asynchronous Programming has the information that you need to know to improve the performance.
In my experience those are my recommendations:
Create a main threat to handle the main program.
Create a class to handle the Socket Server, which implements an asynchronous process to accept connections, using the methods BeginAccept and EndAccept, here is a sample of how to use it.
Create another class to handled the socket connections, which has as a property the Socket object.
2.1 create a method to start the Reading process, which will be called by the Server class to start the communication between the endpoints. This methos will start the process of read in an asynchronous way.
2.2 To read and write in an asyncrhonous way, it is necessary to get the NetworkStream from the socket, and use the methods BeginRead and EndRead, to receive data, and BegineWrite and EndWrite to send data. Here there is the documentation.
In the case that your service only needs to connect to a Server, ignore the step 1and implement the Client class to start the connection to an specific EndPoint.
Use a collection class, as can be a Dictionary, Key-Value-Pair collection, to store each Client Class and use the socket ID as the key to access to each Client Class.
Due each Client Socket handles it own socket, i use to implements a way to reconnect at the same Client Socket, i this way each Client is responsable for itself.
The main program will be responsable to create each Client Server and set the EndPoint of each client, as you need, and start to connect each of them. In this case, TCPClient allow you begin an asynchronous process for connect, using the methods BeginConnect and EndConnect.
Here you can see more details about this issue.
I hope this might be useful for you.
To handle such a large volume of traffic you need to do a few things.
Assumptions
You are connecting to another client’s server.
You have a large volume of web traffic from either multiple machines or from multiple working processes on any given machine.
You know how to create TCP client server objects and handle the connections.
For less than 80 worker threads across your servers:
Because each thread processes synchronously, you only need to use a single connection for each thread.
If no single web server is running more than 20 worker processes, then you can designate a single port for each server to use. Stick the port in your web.config file as a variable and use that when creating connections. You will never hit the limit.
Store your connection in a shared object that the entire app can use (could put this in your BLL layer) and if you have a connection error, re-create a new connection on that thread.
For more than 80 worker threads across your servers:
Do the same as the last step but at this point you either need to negotiate for more connections or you will add a new layer in between your application and the server you wish to reach.
This second layer acts as a broker for the two sides and can manage a pool of connections instead and draws off a connection each time you need to access Server-A and puts it back into the pool when finished.
Anytime you connect to the broker application, spawn a new thread to do the processing until the connection is dropped or closed.
Keep track of your open connections and viola you can have as many clients as you need but your bottleneck will be those 80 connections out even if you have hundreds or thousands in.

Polling over thousands of TCP sockets

I need to connect to thousands of clients over TCP on a proprietary protocol to acquire data cyclically. I need to write a .NET server application in C#.
The first attempt was to create for each tcp socket an own thread, which works but needs a lot of cpu usage.
I found out that it would be a better idea to use the .NET threadpool instead. As far as I understand (http://msdn.microsoft.com/en-us/library/ms973903.aspx) I could use timers in order to get each socket acquire the data cyclically in a given period (like 1 sec). This does not work for me because the sockets time out once the connection was openende because there are a lot of more sockets which have to be opened before it's the open sockets turn again.
Another try was using asynchronous callbacks. This would work for me but I don't know how to get the sockets acquire data cyclically???
Try using Socket's high performance API which allows simultaneously receiving data on a very large number of sockets, without using one thread per socket. At the bottom of the article there's a link to a complete sample. There's also a sample in the MSDN article for the SocketAsyncEventArgs class.
Why not populate a queue with the addresses you need to poll and have your thread pool take items off the queue to process?
Once you are done with an item push it to the back of the queue.

When to use different ports for client-server application?

When will I normally need different ports for client-server communication?
(This question is for C# and general socket programming).
I have implemented and been using a simple C# client-server application. Basically:
server listens for client
on accepted/connected
server spawn client thread -
server waits for client to talk
client talk
server respond
client talk
server respond etc.
if client stops talking, then server blocks in NetworkStream.Read() mode forever in that spawned thread unless client-side disconnects.
I am now thinking of the situation where both sides keeps quiet until some event happen on either side then only will the client or server sends data across. As such both needs to be in NetworkStream.Read mode concurrently somehow and also be able to send to each other at the same time (if the event happens on both sides simultaneously).
Do we need different ports in this case or can both client and server be in NetworkStream.BeginRead mode without risking a problem with NetworkStream being in both writing and sending mode at the same time?
Thanks.
Excellent question. I have written more than one app with that architecture. When you need to have bi-directional communication, you need two connections (of course, in two different ports) between client and server:
Connection where requests flow from client to server
Connection where requests flow from server to client
That way, both sides will have a NetworkStream ready to be read. And you notice the level of independence between the two flows, allowing you more control over your bi-directional request handling code.

multiple threads writting to a same socket problem

My program uses sockets for inter-process communication. There is one server listening on a socket port(B) on localhost waiting for a list of TCP clients to connect. And on the other end of the server is another a socket(A) that sends out data to internet. The server is designed to take everything the TCP clients send him and forward to a server on the internet. My question is if two of the TCP clients happened to send data at the same time, is this going to be a problem for the server's outgoing socket(A)?
Thanks
The MSDN docs recommend that you use BeginSend and EndSend if multiple threads will be using the same socket to transmit data.
So I would suggest that you either use those methods or write outgoing data to a synchronized queue, from which a single thread will then pick data off of the queue and send it over socket(A)
You don't describe how you multiplex the traffic of multiple client streams onto a single outgoing stream. Just arbitrarily putting chunks of client traffic into the stream is guaranteed not the work. The receiving end on the opposite end of the intertube will have no idea what bytes belong to what conversation.
I'd recommend you focus on the opposite end first. What machine is out there, what does it do, what does it need to know about the multiple clients at the local end.

Single socket multiple clients architecture

I have to maintain a single persistent socket connection to a payment gateway and use it to send financial messages and receive confirmation for the same. My application will be then used by various clients and so I need to devise a way to handle them concurrently and handle issues such as timeouts and retries etc.
Right now, my main issue is with accessing the socket... should I just lock the send and recv per message request and response or set up a queuing system and match them? I'll also be sending periodic echo messages on another thread.
Oh, and I am planning to do it in C#. I would appreciate some general advice on this issue.
You need a persistent socket to the payment gateway, ok. By that I assume you mean it must stay connected.
Then you need to create a listener socket to listen for connections from your clients. Then act as a translator between the two.
I'm not sure I understand what you mean by "lock the socket". Lock it how?
Unless the protocol for the payment gateway is intended for multiple concurrent operations, you probably don't want to send more than one request at a time. This would mean a queue of some sort, or a thread for each request using some kind of mutex or semaphore to control access. A queue is more efficient in most cases.
I did this exact thing (if I understand you correctly). I have a server that connects to some target devices over sockets and then clients hook up to the server to talk to different target systems. Is this (kind of) what you want? I have multiple clients talking to the same socket through the server.
In my server I keep a list of connected clients and a list of connected targets. When a client requests a target I add it to a matrix that is essentially a dictionary of connections because several clients can talk to one target at the same time. The server then pumps messages between clients and targets entirely asynchrounously and I use transaction IDs to keep track of the messages. So that when a target answers a request the server knows to which client to send the answer.
I'm not sure this is what you want but maybe what I did will help you a little on your way anyway. If I'm on the right track I can elaborate further.

Categories

Resources