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.
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 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.
I've been working on a complex server-client system in C and I'm not sure how to implement the socket communication.
In a nutshell, the system is a server application which communicates with a database and uses a UNIX socket to communicate with one or more child processes created with fork(). The purpose of the children is to run game servers. The process of launching a game server is like this:
The server/"manager" identifies a game server in the database that is to be made. (Assume database communication is already sorted.)
The manager forks a child (the "game controller").
The game controller sets up two pipe pairs, then forks, replacing its child's stdin with a pipe, and it's stdout and stderr with another pipe.
The game controller's child then runs execlp() to begin running the actual game server executable.
My experience with sockets is fairly minimal. I have used select() on a server application before to 'multiplex' numerous clients, as demonstrated by the simple example in the GNU C documentation here.
I now have a new challenge, as the system must be able to do more: the manager needs to be able to arbitrarily send commands to the game controller children (that it will find by periodically checking the database) and get replies, but also expect incoming arbitrary commands/errors from them and send replies back.
So, I need a sort-of "context" system, where sockets are meaningful only between themselves. In other words, when a command is sent from the manager to the game controller, each party needs to be aware of who is asking and know what the reply is (and, therefore, which command it is a reply to).
Because select() is only useful for knowing when we have incoming data, and a thread should block on it, would I need another thread that sends data and gets the replies? Will this require each game controller, although technically a 'client', to use a listening socket and use select() as well?
I hope I've explained the system and the problem concisely; I will add more detail if required. Thanks!
Ok, I am still not really sure I understand exactly where your trouble is, so I will just spout off some things about writing a client/server app. If I am off track, just let me know.
The way that the server will know which clients corresponds to which socket is that the clients will tell the server. Essentially, you need to have a log-in protocol. When the game controller connects to the server, it will send a message that says "Hi, i am registering as controller foo1 on host xyz, port abc..." and whatever else the server needs to know about its clients. The server will keep a data structure that maps sockets to client metadata, state, etc. Whenever it gets a new message, it can easily map from the incoming host/port to its metadata. Or your protocol can require that on each incoming message, the will client send the name it registered with as a field.
Handling the request/response can be done several ways. First lets deal with the networking part of it on the server side. One way to manage this, as you mentioned, is by using select (or poll, or epoll) to multiplex the sockets. This is actually usually considered the more complicated way to do things. Another way is to spawn off a thread (or fork a process, which is less common these days) for each incoming client. Each spawned thread can read its own assigned socket, responding to messages one at a time without worrying about the fact that there are other clients besides the own it is dealing with. This simple one to one thread to socket model breaks down if there are many clients, but if that is not the case, then it is worth consideration.
Part 2 really covers only the client sending the server a message, and the server replying. What happens when the server wants to initiate communication? How does it do it and how does the client handle it? Also, how do you model the model the communication at the application level, meaning assuming we have the read/write part down, how do we know what to send? You will probably want to model things in terms of state machines. There is also a lot more to deal with like what happens when a client crashes? What about when the server crashes? Also, what if you really have your heart set of using select, perhaps because you expect many client? I will try to add more to this answer tomorrow.
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.
I need to detect the presence/absence of internet connection. More precisely, let us suppose that the application is broken up into 2 parts - A and B.
A is responsible for checking whether or not the system is connected to the internet. If it finds that there is no connection, it starts up part B. And as soon as it detects that there is a network connection, it kills B and continues its own work.
What would be the best way to do the A part of the application? Continual pings sounds hideous. There has to be a better way of doing this (preferably in C).
With sufficient privilege you can test the various network interfaces and examine their state. This would tell you if any of the interfaces was connected to a network and operating. However, this won't tell you if the connection is actually usable, i.e., connected to the internet (or your local net if that's all you need). I don't know of anyway to do that short of actually using it.
Using ICMP (ping) can be useful at a low level, but presumably what you need is a connection to an actual endpoint via TCP/IP to do real work. I would say that you should change the design of your application so that B is responsible for indicating when it is unable to continue due to the absence of resources that it relies on -- network or otherwise. A and B should communicate so that A is aware of the situation and is able to either kill B or respond to B terminating itself and thus continuing its work.
A lot of companies have measures in place to prevent outgoing ICMP requests, TCP connections to ports other than 80/443 for example, or even to prevent you from reaching the internet directly by (transparently) proxying your traffic.
Under an internet connection I would understand any way to contact the outside, be it UDP, TCP or ICMP. Depending on what your application needs to contact the internet for, I would suggest to check over the same protocol, as that is the only thing that matters to your app.
If your application uses HTTP to communicate to an external source, try to connect to a few sites you would suspect to not be blacklisted and that have a reliable uptime. Like google.com, microsoft.com, apple.com, and so on...
Edit:
I am unsure what the specifics are, so let me give you an example with a hypothetical situation.
Application A collects data on the system it is running on and forwards it to a Web Service listening on yourserverhost.yourcompany.com:80
Application B would basically take over the job of the Web Service when it is down and log everything so no data is lost.
When all is well, App A will be sending the data to your web service
Once this connection drops, you immediatly launch App B (the obvious remark here would be, why not keep App B running as a failsafe)
App A connects to App B and forwards what it had been buffering
App A continues to try to reestablish the connection to your Web Service and once it is back up will request App B to stop
If the problem you are facing is nothing like this, please provide a more concrete description of what App A and App B are supposed to be doing. I will be more than happy to help.
In your code, you have to check whether the internet connection exists by using a socket to open a connection to a website.
Firstrun: Ask user to input the network parameters, like proxy settings. Save this info.
Next runs: Use these settings to check for the Internet connection. You may simply do a DNS search.
If results are negative, ask user to check settings.
Check whether the cable is connected , if so ping your internet connection to any host as google.com.
ping google.com