I'm learning about TCP/IP and am trying to use it to execute different commands on my server.
I thought i'd start small and build up. I've got a current example running which has a server and client connect, and then the server sends the current time to the client.
Now i want to make it such that the server can handle multiple clients.
How can I do this? I think i could use fork, but is there a way to do it without having multiple processes to worry about?
Are there any good primers on this sort of thing, or could you provide some instructions on how to modify my existing code?
Thanks,
glibc Manual has a nice example. The missing code bits can be found earlier in the chapter. The nice thing about the example is that you do not need multiple threads
I would recommend the use of threads:
One server thread has the sole purpose of listening at the server socket for incoming connections. Once a connection is received, it is passed off to a worker thread, while the server keeps listening.
One or more worker threads. These threads will do the majority of the work. You can choose to use one thread per socket, or you can use the select function to allow one thread to handle multiple sockets.
I don't know any primers off the top of my head, sorry.
Take a look at Erik's answer on this other question. You don't really need to do multithreading.
Related
I'm a learning C and just started reading about sockets.
I was wondering if a program can be coded to be both a server and a client at the same time. For example, a program starts off as a server but if it wanted to connect to another server, it could, in parallel, start a client to connect to other program's servers, while maintaining it's server status for others to connect too.
If so, how can that be done? With different processes?
Thank you guys!
This is one of the use cases for "threading" where there are multiple execution instances performing different jobs in concert. https://simple.m.wikipedia.org/wiki/Thread_(computer_science)
Yes, it can.
There is absolutely nothing which stops this.
If you want to manage more than one socket from the same process, you might find the poll function useful, or select on Windows. (select also works on Linux but poll is better in my opinion)
I have a program that needs to:
Handle 20 connections. My program will act as client in every connection, each client connecting to a different server.
Once connected my client should send a request to the server every second and wait for a response. If no request is sent within 9 seconds, the server will time out the client.
It is unacceptable for one connection to cause problems for the rest of the connections.
I do not have access to threads and I do not have access to non-blocking sockets. I have a single-threaded program with blocking sockets.
Edit: The reason I cannot use threads and non blocking sockets is that I am on a non-standard system. I have a single RTOS(Real-Time Operating System) task available.
To solve this, use of select is necessary but I am not sure if it is sufficient.
Initially I connect to all clients. But select can only be used to see if a read or write will block or not, not if a connect will.
So when I have connected to say 2 clients and they are all waiting to be served, what if the 3rd does not work, the connection will block causing the first 2 connections to time out as well.
Can this be solved?
I think the connection-issue can be solved by setting a timeout for the connect-operation, so that it will fail fast enough. Of course that will limit you if the network really is working, but you have a very long (slow) path to some of the server(s). That's bad design, but your requirements are pretty harsh.
See this answer for details on connection-timeouts.
It seems you need to isolate the connections. Well, if you cannot use threads you can always resort to good-old-processes.
Spawn each client by forking your server process and use traditional IPC mechanisms if communication between them is required.
If you can neither use a multiprocess approach I'm afraid you'll have a hard time doing that.
I am working on a UDP server/client application.
I want my server to be able to handle 40 clients at a time. I have thought of creating 40 threads at server side, each thread handling one client. Clients are distinguished on the basis of IP addresses and there is one thread for each unique IP address.
Whenever a client sends some data to a server, the main thread extracts the IP address of the client and decides which thread will process this specific client. Is there a better way to achieve this functionality?
There are different approaches for scale able server application, one thread per client seems good if no of clients are not many, another most efficient approach to accomplish this task is to use thread pool. These threads are work as task base when ever you have any new task assign this task to free worker thread.
Take a look at this project, I think it is very helpful to start with: http://www.codeproject.com/Articles/16935/A-Chat-Application-Using-Asynchronous-UDP-sockets
With IPAddress.Any, we specify that the server should accept client
requests coming on any interface. To use any particular interface, we
can use IPAddress.Parse (“192.168.1.1”) instead of IPAddress.Any. The
Bind function then bounds the serverSocket to this IP address. The
epSender identifies the clients from where the data is coming.
With BeginReceiveFrom, we start receiving the data that will be sent
by the client. Note that we pass epSender as the last parameter of
BeginReceiveFrom, the AsyncCallback OnReceive gets this object via the
AsyncState property of IAsyncResult, and it then processes the client
requests (login, logout, and send message to the users). Please see
the code attached to understand the implementation of OnReceive.
A better way would be to use the Proactor pattern (take a look at Boost.Asio library), instead of creating thread per client. With such an approach your application would have much better scalability and performace (especially on platforms that have native async i/o)
Besides, with this technique the threading would be de-coupled from the concurrency, meaning that you don't necessarily have to mess with multi-threading with all its complications.
there.
I am trying to program a server.
The server receive some information from client
and it sends the information to the other server and it receive the response.
Do I need to use select() on this case?
or Pthread only is enough to do this.
my server has many clients connecting concurrently
please answer me kindly.
And if there is, please tell me the source code or site that I can refer to
One approach to implementing a server that handles multiple clients is to create a pthread for each client connection, so that you can read/write each connection in a dedicated thread. It sounds like what you're asking is "if I have a pthread for each client connection, do I still need to use select?"
In a very simple server you might be able to dispense with select: the connection thread looks something like:
do {
read(conn, cmd);
response = process(cmd);
write(conn, response);
} while (cmd != DONE)
But, even with a dedicated client thread, you may find that you still want to use select to check for available input before calling read on the client connection. For example, if you need to be able to implement an idle timeout on your connection, you won't want to just do a blocking read.
I'm not sure what you mean by using pthread to communicate between client and server - my experience of pthread is the POSIX Thread library which doesn't relate to communications....
Documentation and examples of how to use select are broadly available:
http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/lr2/select.htm
http://www.lowtek.com/sockets/select.html
are examples of what you might find by searching "select c" using google....
First of all, the environment I'm working on is Windows 7 and Visual Studio 2010.
I already wrote a server that uses the select method to retrieve data from more than one client.
Also I wrote a client that connected to the server above, by running (client.exe localhost 4444 Peter). "Peter" is the username that this user wants to use.
Now let's say we have two users connected on the server. Each of them has the ability to run the command /help. This returns some other commands that the user can use. One command of these is /listusr that returns all the users on the server.
One other command is the /talk2 and here is where my problem-question begins. I want to let the user choose to which of the other users want to talk. E.g if you want to talk to Peter, you give /talk2 Peter.
How am I going to start something like this? How will the server send the message from me to Peter (I have to add here that when a new user connects, the server saves his/her username and his/her socket number in a struct)?
Do I need to create new threads for each conversation or new processes? Can someone give me some hint or advice to continue my project? I'm little confused on how to manage at this point.
Neither. Your server should maintain some kind of data structure that matches a user id to a client socket handle. When a request comes in with the /talk2 command, the server should look up the corresponding socket handle for that userid and should simply relay that message using send().
A scalable way would be your sever is just responsible to tell both clients the IP address of the other side, and then Peter and you establish the connection so you can talk.
If you really want to have the sever transfer the conversation, you need to consider the following to gain a better scalability:
Use UDP instead of TCP
Use thread instead of process
Spawning a new process would be an ordeal for the server if the number of users interacting at a time are high. But on the other hand it will be simpler to code.
Threads do provide scalability, but then you must be extra careful in your code not to do anything silly. (For example, sending wrong chats to the wrong guys.)
Use select/poll techniques (I am not sure how they perform in the Windows environment, but it works cool with Linux.)
UDP will reduce transmission time, but I am not too sure if it's a good idea. Since you said you already have a code, it would be great pain to switch to UDP.
Just sending the address of required client is also a feasible idea. It reduces a lot of effort from the server, but now you will require dedicated clients.
Try each of them and check which one works best for you. It's a design problem, so there can't be a hard and fast solution. It will depend on the usage of your application. You may also want to use (may be you are already using) the sendto and recvfrom functions.