I am building a client/server protocol using libwebsockets library. In the poll thread, each callback on incoming packets triggers a certain method to either save data, respond accordingly, and so on. However, if there are other incoming packets that would trigger LWS_CALLBACK_CLIENT_RECEIVE, the processing of the previous task is left undone.
Is there a way to finish the tasks before dealing with the packets received? Should LWS_CALLBACK_CLIENT_RECEIVE start new threads to handle the processing of data?
This was a typical case of multi-threading: one thread receives the packets, fills a buffer and goes back to listening for incoming packets. Working threads will empty the buffer.
Related
I'm receiving a large amount of data over a TCP socket which I'm looking to send to a number of additional sockets (essentially echoing the contents of the first socket). My requirements are as follows:
Any data received over the read socket must be sent reliably (in order of arrival) to the write sockets
Writes must not block reads from the primary socket under any circumstances
Disconnections/broken pipes should never interrupt reading from the inbound socket
Currently I'm using a multi-threaded system that maintains a linked list of data read from the inbound socket, and have threads for each outbound socket. When messages arrive via the inbound socket I signal the outbound socket threads to create a copy of the linked list from the main thread and broadcast the data without interrupting operations. My linked list structure maintains an fd_set of file descriptors on the main thread, which it uses to determine when a message has been successfully copied and broadcast by each outbound socket (thus removing it from the list).
This is obviously a lot of moving parts, and I wanted to see if I was missing something fundamental that could be used in a situation such as this.
What you want to do is similar to what I've been doing for the past two decades.
Don't lock and copy the entire list. Instead, have each sending thread read-lock just the element it's currently sending. Have the receiving thread write-lock each new element and perform element deletion. Allow for a long list to accommodate transient bursts.
You can make the list persistent by memory-mapping it to a file.
Good luck. The task is non-trivial.
I am working on improving the performance of a network application written in C running on linux systems.
The program as it is written now it reads a packet from a socket interface, it does some processing on it and then it adds it to a send queue.
I am pretty new to multi threading programming but I am familiar with the basic concepts (mutex, conditional signals etc).
I am trying to implement a solution where a set of worker threads are passed what is read from the interface and they do the work that follows.
My question is how could I ensure that, if first thread reads the first packet and the second thread reads the second packet, the order in which the packets are added to the send queue are in the same order as read.
There are lots of ways to solve this. Different ways have different trade offs. Things to consider are if you want to have a static number of worker threads, how many worker threads, and how perfect you want the solution to be.
If all worker threads are to receive their data packets directly via a call to read or recv then:
pthread_mutex_lock(&the_mutex);
do
{
read_size = read(sock, buf, buf_size);
if (read_size > 0)
{
my_count = ++packet_counter;
break;
} else
{
// figure out how to handle different failures here
}
} while (1);
pthread_mutex_unlock(&the_mutex);
results = do_work(buf, read_size);
enqueue_results(my_count, results);
Would work, where enqueue_results() would put the results into a priority queue that can handle wrapping around of the key (which isn't that difficult to do since you just order by last_sent_count-this_count rather than using this_count directly for the queue ordering).
Then another thread would needs to wait on the next reply to be sent to become ready and send that.
You could get a lot fancier, but you should give this a try.
Just code what you want. Outbound packets can be inserted into a queue in order, and the sender can wait if the packet it needs to send next isn't at the head of the queue.
When you say you add it to the send queue, does another thread that you have control over remove it from this send queue to later send or is this outside your control. If the former you can use a priority queue for the second queue instead of a traditional first in first out queue. If the key to the priority queue is some global counter, the sender will always pull the smallest/next value. Now if that smallest value isn't the next value you can have the thread pulling from the sender thread wait for the next value. Depending on the priority queue implementation you can also just peek into the queue to see the next value and then conditionally wait until another insertion into the queue.
The program could use separate receive and send queues for each thread. The receiving thread would queue packets to the processing threads in round robin order. Each processing thread would dequeue a packet from its receive queue, process the packet and queue the processed packet to its send queue. The sending thread would dequeue processed packets from the processed send queues in round robin order.
I'm using send on Linux std socket to write a packet over network. Send call, buffers data and "always" return values greater than 0. Send Pass the problem to the operating system and the lower level.
How can i stop the send call and wait for the delivery of the packet to the other endsystem? Waiting for the TCP ACK or something like that?
if (send(broker->socket, packet, sizeof(packet), 0) < sizeof(packet)){
return -3;
}
The test will like:
start to send packet,remove the ethernet,reattach.
Thanks, sorry for my bad english.
There's no real robust way to find out if the remote peer acked your data. In fact, even if the remote TCP acks your data that doesn't mean the remote process read it. The simplest method is to implement a sort of application-layer ACK where the peer sends back a byte signaling "ok, got it".
You call send and it returns almost immediately
At this point the kernel starts working, trying to push the data
You call recv which blocks
The remote side receives the data and sends some data back, acknowledging it
Your recv unblocks
At this point you can be certain the remote side received your data.
I have to receive data from 15 different clients each of them sending on 5 different ports. totally 15 *5 sockets.
for each client port no is defined and fixed. example client 1 ,ports 3001 to 3005. client 2 ,ports 3051 to 3055 etc. They have one thing in common say first port (3001 , 3051) is used to send commands. other ports send some data.
After receiving the data i have to check for checksum. keep track of recvd packets, Re request the packet if lost and also have to write to files on hard disk.
Restriction I cannot change the above design and i cannot change from UDP to TCP.
The two methods i'm aware of after reading are
asynchronous multiplexing using select().
Thread per socket.
I tried the first one and i'm stuck at the point when i get the data. I'm able to receive data. I have some processing to do so i want to start a thread for each socket (or) for sockets to handle (say all first ports, all second, etc ..i.e.3001,3051 etc)
But here if client sends any data then FD_ISSET becomes true , so if i start a thread ,then it becomes thread for every message.
Question:
How to add thread code here, Say if i include pthread_create inside if(FD_ISSET .. ) then for every message that i receive i create a thread. But i wanted a thread per socket.
while(1)
{
int nready=0;
read_set = active_set;
if((nready = select(fdmax+1,&read_set,NULL,NULL,NULL)) == -1)
{
printf("Select Errpr\n");
perror("select");
exit(EXIT_FAILURE);
}
printf("number of ready desc=%d\n",nready);
for(index=1;index <= 15*5;index++)
{
if(FD_ISSET(sock_fd[index],&read_fd_set))
{
rc = recvfrom(sock_fd[index],clientmsgInfo,MSG_SIZE,0,
(struct sockaddr *)&client_sockaddr_in,
&sockaddr_in_length);
if(rc < 0)
printf("socket %d down\n",sock_fd[index]);
printf("Recieved packet from %s: %d\nData: %s\n\n", inet_ntoa(client_sockaddr_in.sin_addr), ntohs(client_sockaddr_in.sin_port), recv_client_message);
}
} //for
} //while
create the threads at the startup of program and divide them to handle data, commmands e.t.c.
how?
1. lets say you created 2 threads, one for data and another for the commands.
2. make them sleep in the thread handler or let them wait on a lock that the main thread
acquired, seems to be that mainthread got two locks one for each of them.
3. when any client data or command that got into the recvfrom at mainthread, depending on the
type of the buffer(data, commands), copy the buffer into the shared data by mainthread and
other threads and unlock the mutex.
4. at threads lock the mutex so that mainthread wont' corrupt the data and once processing is
done at the threads unlock and sleep.
The better one would be to have a queue, that fills up by main thread and can be accessed element wise by the other threads.
I assume that each client context is independent of the others, ie. one client socket group can be managed on its own, and the data pulled from the sockets can be processed alone.
You express two possibilities of handling the problem:
Asynchronous multiplexing: in this setting, the sockets are all managed by one single thread. This threads selects which socket must be read next, and pulls data out of it
Thread per socket: in this scenario, you have as many threads as there are sockets, or more probably group of sockets, ie. clients - this the interpretation I will build from.
In both cases, threads must keep ownership of their respective resources, meaning sockets. If you start moving sockets around between threads, you will make things more difficult that it needs to be.
Outside the work that needs to be done, you will need to handle thread management:
How do threads get started?
How and when are they stopped?
What are the error handling policies?
Your question doesn't cover these issues, but they might play a significant role in your final design.
Scenario (2) seems simpler: you have one main "template" (I use the word in a general meaning here) for handling a group of sockets using select on them, and in the same thread receive and process the data. It's quite straightforward to implement, with a struct to contain the context specific data (socket ports, pointer to function for packet processing), and a single function looping on select and process, plus perhaps some other checks for errors and thread life management.
Scenario (1) requires a different setup: one I/O thread reads all the packets and pass them on to specialized worker threads to do the processing. If processing error occurs, worker threads will have to generate the adhoc packet to be sent to the client, and pass it to the I/O thread for sending. You will need packet queues both ways to allow communication between I/O and workers, and have the I/O thread check the worker queues somehow for resend requests. So this solution is a bit more expensive in terms of developement, but reduce the I/O contention to one single point. It's also more flexible, in case some processing must be done against data coming from several clients, or if you want to chain up processing somehow. For instance, you could have instead one thread per client socket, and then one other thread per client group of socket further down the work pipeline, with each step of the pipeline interconnected by packet queue.
A blend of both solution can of course be implemented, with one IO thread per client, and pipelined worker threads.
The advantage of both outlined solutions is the fixed number of threads: no need to spawn and destroy threads on demand (although you could design a thread pool to handle that as well).
For a solution involving moving sockets between threads, the questions are:
When should these resources be passed on? What happens after a worker thread has read a packet? Should it return the socket to the IO thread, or risk a blocking read on the socket for the next packet? If it does a select to poll the socket for more packets, we fall in scenario (2), where each client will has its own I/O thread when there is network trafic from all of them, in which case what is the gain of the initial I/O thread doing the select?
If it passes the socket back, should the IO thread wait for all workers to give back their socket before initiating another select? If it waits, it takes the risk of making unserved client wait for packets already in the network buffers, inducing processing lag. If it does not wait, and return to select to avoid lag on unserved sockets, then the served ones will have to wait for the next wake up to see their sockets back in the select pool.
As you can see, the problem is difficult to handle. That's the reason why I recommend exclusive sockets ownership by threads as described in scenarii (1) and (2).
Your solution requires a fixed, relatively small, number of connections.
Create a help procedure that creates thread procedures that listen to each of the five ports and block on the recvfrom(), process the data, and block again. You can then call the helper 15 times to create the threads.
This avoids all polling, and allows Linux to schedule each thread when the I/O completes. No CPU used while waiting, and this can scale to somewhat larger solutions.
If you need to scale massively, why not use a single set of ports, and get the partner address from the client_sockaddr_in structure. If the processing takes a material amount of time, you could extend it by keeping a pool of threads available and assign a new one each time a message is received and continue processing the message thereafter, and adding the thread back to the pool after the response is sent.
I want to design a TCP server which listens for x clients. X is small, say around 10 and its fixed. Clients may connect at any time. Once the connection is established (accept() successful) I spawn a thread for each client and handle them.
In this handle() function I want to send commands to client and receive the data accordingly.
Problem:
Once a command has been sent from the server the client responds by sending data continuously. How do I send a command back to the client to stop it? As with the current code I'm in a loop receiving data from the client.
I don't know how to send the command from server thread while receive is in progress, like should I need to have another thread (to send cmds) once the connection is established?
How to continuously receive data from clients and also send commands at the same time? Sending commands to each client based on user inputs. (Say user wants client1 to start sending data, then I have to send START to client1. And user wants to stop the client1 from sending, so I need to send STOP to client1 And if user wants data3 cmd to be sent to client 4 then send command DATA3 to client4 etc. How do identify the client in this case? Basically forming a small protocol**
The below code is working where I can listen on socket and client connects and sends data. I'm not sure of how to send user inputted commands to the right client (say client4) and also receive at same time.
If you want to really continously stream data and in parallel want to exchange commands you won't get around an addtional connection to establish the command channel. The alternativ would be some kind of multiplexing. Stream a chunk of data, check for commands, stream the next chunk, check for commands again ... - complicated and error prone as the stream is continously interupted ...
The stone old ftp protocol does something similar: http://en.wikipedia.org/wiki/Ftp and https://www.rfc-editor.org/rfc/rfc959 (see ascii art in chapter 2.3)
Presuming you want to have another thread initiate the request to send a command, you can accomplish what you want using standard asynchronous i/o, adding in another channel - a pipe - to receive commands from the other thread. Pseudocode:
Master thread:
while(1) {
newsocket = accept(listen socket)
pipefds = pipe()
new thread(Receiver, newsocket, pipefds.read)
}
Receiver thread:
while(1) {
readfds = [ pipefds.read, newsocket ]
poll( readfds ) // wait for there to be data on one of the fds
if (data ready on newsocket) {
read (newsocket)
process data
}
if (data ready on pipefds.read) {
read (pipefds.read)
send command
}
}
Commander thread:
write (pipefds.write, command)
The select in the main Receiver loop will wake up whenever there is data to read on the socket, OR if another thread has sent a command that needs to be sent to the remote connection.
Key syscalls to look up info on are poll (or select), and pipe.
WOO HOO! You've decided to dive into a pretty hairy subject, my friend.
Let me first rephrase your problem: your program can only wait for one thing at a time. If it's waiting on receive, it can't be waiting on send. So you just can't send and receive at the same time.
This is solved by multiplexing: waiting on multiple things.
Googling keywords: io, multiplexing, select, poll.
SO related question: read and write to same socket (TCP) using select
Another approach is to enter a nonblocking-read -> nonblocking-write -> sleep loop. This is obviously less than optimal, but may be enough for your case.
I've had some fun in the past designing my own bi-directional protocol for low level devices that can't communicate at the same time. One method you can use is mutual yielding: establish a mechanism for passing messages to and from the client and server. Stream any commands or messages you need to send, then yield the stream to the other side. The other side will then stream any messages or commands, then yield the stream to the original side. The only problem with this mechanism is that it's very laggy with high-ping connections, such as international internet connections.
This has been mentioned already, but I might as well rehash it. Computers have multiplexing built in to their networking hardware already, so you can do "concurrent" send/recv calls. Just run a pair of threads for each connection: a recv thread and a send thread. This should be the most robust solution.