Sockets - send and receive - c++

I'm currently writing a chat server in C++. When a user connects to it, I open a socket and I create two threads, one to receive and one to send data.
Now my question:
Do I have to check if the other thread is currently using the socket, or will the send/recv function just wait until the socket is ready?

Sending and receiving from TCP socket simultaneously should be entirely fine. (barring any possible OS bugs)

Socket send and receive are independent. You do not need to worry about interleaving them yourself.

Related

Multiple writes on same socket c++

I'm currently trying to develop a server and some clients which communicate with each other using something like a proxy in the middle. The "proxy" will have sockets opened to every client and server on the system. This means that I'm currently using threads to keep all the connections opened. Every time a client decides to send a message it uses its socket with the proxy and sends the message. Then the proxy will propagate the message to every other node using the respective socket.
As you can see, a node can be receiving messages by having the proxy writing on the socket or a node may want to send messages by writing on the socket.
How do I guarantee that the content in the socket does not get overwritten ? Do I have to use mutexes to lock the access to the socket ? What is a good practice to solve this problem ?
Connections are bi-directional. Content going one way does not overwrite content going the other way. No mutex is needed for this.
Besides, you couldn't use a mutex anyway, as both sides of the connection are separate.

Set TCP client socket to non-blocking: Server vs client

I have a question regarding non-blocking sockets in TCP connections.
I have implemented two c++ classes, one for the tcp server and one for the client. The server has two sockets file descriptors, one for the server and one for the client. The client has one socket file descriptor.
My server runs asynchronously and my client runs at a fixed rate. Therefore I would like to have a non-blocking socket for sending data from the client to the server, s.t. the client can send data at a fixed rate without stalling and the server asynchronously reads all data that has been buffered meanwhile.
So my question is: Does it make a difference, if I set the client socket to non-blocking in the client or the server class? (using fcntl(this->newsockfd_, F_SETFL, fcntl(this->newsockfd_, F_GETFL, 0) | O_NONBLOCK), where this->newsockfd_ is the client's socket file descriptor in both classes)
I tried this in my programm and it seemed like setting the client socket to non-blocking in the client-class didn't do the trick, but setting it in the server-class did. However, I don't understand why this should make a difference.
If your socket is set to non blocking mode, you will get just that. It will never block. But that does not mean that your api calls will succeed.
There are buffers that are being used behind the scenes and if they are full, which would mean in blocking mode that the socket would block, you will get a return code EWOULDBLOCK, which means that your sent has failed. This means that you basically have to wait for the buffers to empty and then try again.
Your idea of sending at an even rate despite of the server rate to receive, is impossible. You cannot have a client sending at a fixed rate. The whole idea of TCP is that there is a constant negotiation between client and server and the speed will be heavily depending on the network conditions. Congestion and the like.
Moving to non blocking sockets creates some problems of its own. You have to detect that the send fails, you have to check if the socket becomes writeable again, you have to store the bytes that you tried to send, and reattempt a send as soon as the socket becomes writable again.
There is a lot of difference on both client and server between working with blocking and non blocking sockets. non blocking sockets are in my opinion more difficult to be dealt with. You need the select api, with a timeout very likely to detect all the possible socket states. In case of blocking sockets, you can just use a socket in a thread, and if the socket blocks, it is just the thread that will block as well. If your gui is on a different thread, the GUI will be responsive.
Since your client is only sending data the non-blocking setting will not effect it. According to the excellent beej.us guide on socket programming, only calls to accept() and recv() are effected by the non-blocking setting. Since only your server is calling these you are seeing the change on your server code. If your client received data then the non-blocking setting would effect it and you would have to use select() to check if there is data and read from it accordingly.

C++ receive UDP packet on same port sent from

I have 2 UDP sockets (SOCKET), one for sending and one for receiving on a Windows machine. They both work well, but the trouble is that a program that is receiving messages from my send socket replies to the same port which sent the message.
I know that if I don't bind the send socket, using sendto will pick an ephemeral port to send on.
I'd like to know if it is possible to any of the following, and if so, what is the recommended way to do it:
Bind both the send and receive sockets to a chosen port so that when the external program sends a message back it can be received.
Update the port to which the receive socket is bound in such a way as to receive on the port from which I last sent a message (not sure if this would create a race condition).
Some other correct method.
So far I have tried:
Not binding the send socket (it sends from some open port to the destination port). I can successfully receive messages on that port for as long as it doesn't change, but eventually it does change.
Binding both the send and receive sockets to a desired port. This creates the desired behaviour when I watch the packets using a sniffer, but the receive socket never receives the messages even though I see them being transmitted to the correct port and IP.
Packets are being received from more than one outside entity, and not guaranteed to be in any particular order.
Thank you in advance!
Looks like you are trying to use threads to separate sending and receiving data. I would question this approach, since UDP is so easy to handle in one thread. Nevertheless, you can just use the same socket from both threads if you want (see related question: Are parallel calls to send/recv on the same socket valid?). Just bind(2) it and, optionally, connect(2) it.

Send/Receive TCP/IP on C++

I'm trying to communicate between two computers through the TCP/IP protocol on C++. I'm sending and receiving on the same socket. But there is a problem, I have no indicator that the second computer is trying to send me something.
Is there any flag or indicator that tells me that someone is sending something to me and I have to receive?
Use the select() function to wait for an event on one or more sockets. With a zero timeout, you can also check if there is any data available.
That depends on the particular socket API. In the most common case, you just hang on receive (or with async socket APIs you park a callback) and that will unblock as soon as there is data. Some socket APIs have ways for you to tell whether there's data available to fetch, but the simplest way is simply to receive asynchronously and wait for the socket stack to raise the callback on you.

Signaling all active threads (Windows)

I am faced with a design issue regarding thread synchronization in C++, Windows.
I am writing a server application that starts one listening thread, which should stay active the whole time while the server is up.
When the listening thread gets a connect request, it opens a CONTROL socket and starts a new control thread.
This thread is used to send control data between server and a client, initializing server and all the background software to specific client data and starting data processing.
If the initialization (via control socket) is successful, the control thread will open a new socket, DATA socket, which is then used to pass data from server to client. It will also start two new threads, one which is sending on this new, DATA socket, and the other, which is receiving on the CONTROL socket, waiting if the client wants to terminate connection.
When client terminates connection ungracefully, by terminating application without the call to function which sends the server message to close the connection, here is what should happen:
Any of the threads in execution can detect this event. They will get some sort of error (WSAECONNRESET) while sending or receiving on DATA/CONTROL socket and should then signal all the other threads that they should stop executing (except for the server listening thread).
Which is the most natural way to achieve this type of behavior?
(I am using winsock (winsock2.h) for networking, and standard windows api (windows.h) for threading)
If you're writing a multi-threaded winsock server, you should be looking into IO completion ports. Using an IO completion port is the most scalable way to write a network service on the windows platform.
IO completion port based winsock servers use asynchronous communication, so instead of blocking on a socket, your threadpool receives completion packets when something interesting happens.
In any case, you'll be using WSARecv. When WSARecv returns non zero, call WSAGetLastError(). If you don't have WSA_IO_PENDING, then switch on the error and look for the winsock error code you're interested in.
The winsock error code WSA_OPERATION_ABORTED indicates that a socket has closed, although there are others (e.g. WSAECONNABORTED).
Would suggest a good text on the subject (e.g. Windows via C/C++).
You can use WSAEventSelect() function to associate event object with socket and create one event object for your events, then use these event objects in WaitForMultipleObjects() function, so your thread can wait for socket events and your custom events.