c++ multi client/server chat - c++

I am hitting rock bottom, thinking about a solution for a problem I am having with my chat server and client.
What is supposed to do, client asks for a username, then for a connection request to the user with answer [Y/N].
When hitting yes, client has to connect to server, when it does it needs to go in a separate thread( for handling multiple clients (but my problem is, when more then one user joins( the username of the user current logged in is changed to the last one who joined the chat.
While that is happening (the server shows the username, while on the client screen it disappears and none or all weird signs appear).
What I need also help with is the distribution of the messages to the other clients connected (excluding the user himself)
Code Server:
#include "stdafx.h"
long antwoord;
char chatname[100];
char bericht[498];
char sbericht[498];
using namespace std;
DWORD WINAPI SocketHandler(void*);
//our main function
void main()
{
//here we set the Winsock-DLL to start
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
//here the Winsock-DLL will be started with WSAStartup
//version of the DLL
antwoord = WSAStartup(DLLVERSION, &wsaData);
if(antwoord != 0)
{
WSACleanup();
exit(1);
}
else
{
cout << "WSA started successfully" <<endl;
cout << "The status: \n" << wsaData.szSystemStatus <<endl;
}
//the DLL is started
//structure of our socket is being created
SOCKADDR_IN addr;
//addr is our struct
int addrlen = sizeof(addr);
//socket sListen - will listen to incoming connections
SOCKET sListen;
//socket sConnect - will be operating if a connection is found.
SOCKET sConnect;
//setup of our sockets
//opgezocht op internet - AF_INET bekend dat het lid is van de internet familie
//Sock_STREAM betekenend dat onze socket een verbinding georiƫnteerde socket is.
sConnect = socket(AF_INET,SOCK_STREAM,NULL);
//now we have setup our struct
//inet_addr is our IP adres of our socket(it will be the localhost ip
//that will be 127.0.0.1
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
//retype of the family
addr.sin_family = AF_INET;
//now the server has the ip(127.0.0.1)
//and the port number (4444)
addr.sin_port = htons(4444);
//here we will define the setup for the sListen-socket
sListen = socket(AF_INET,SOCK_STREAM,NULL);
if (sConnect == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
WSACleanup();
}
else
{
cout << "Connect socket() is OK!" <<endl;
}
if(sListen == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
WSACleanup();
}
else
{
cout << "Listen socket() is OK!" <<endl;
}
//here the sListen-socket will be bind
//we say that the socket has the IP adress of (127.0.0.1) and is on port (4444)
//we let the socket become the struct "addr"
if(bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
cout << "bind() failed: \n" << WSAGetLastError() <<endl;
WSACleanup();
exit(1);
}
else{
cout << "bind() is OK!" <<endl;
}
if(listen( sListen, 10) == -1 ){
cout << "Error listening %d\n" << WSAGetLastError() <<endl;
}
//here we will tell what the server must do when a connection is found
//therefor we will create an endless loop
cout << "Waiting for a incoming connection..." <<endl;
//now we let the socket listen for incoming connections
//SOMAXCOMM heeft het nut dat het dan voordurend luisterd naar inkomende verbindingen zonder limiet
int* csock;
while(true)
{
csock = (int*)malloc(sizeof(int));
//if a connection is found: show the message!
if((*csock = accept(sListen, (SOCKADDR*)&addr, &addrlen))!= INVALID_SOCKET)
{
cout << "A Connection was found with :" << inet_ntoa(addr.sin_addr) <<endl;
antwoord = send(*csock, "Welcome to our chat:", 21,NULL);
CreateThread(0,0,&SocketHandler, (void*)csock , 0,0);
cout << *csock <<endl;
}
}
}
//sbericht is the message
DWORD WINAPI SocketHandler(void* lp)
{
int *csock = (int*)lp;
for(;;)
{
antwoord = recv(*csock, sbericht, sizeof(sbericht), NULL);
antwoord = recv(*csock, chatname, sizeof(chatname), NULL);
while(antwoord = recv(*csock, sbericht, sizeof(sbericht), NULL) && (antwoord = recv(*csock, sbericht, sizeof(sbericht), NULL)) )
{
printf("%s\: \"%s\"\n", chatname, sbericht);
antwoord = send(*csock, sbericht, sizeof(sbericht), NULL);
antwoord = send(*csock, chatname, sizeof(chatname), NULL);
}
return 0;
}
}
Client code:
#include "stdafx.h"
using namespace std;
//our main function
int main()
{
//here we set the Winsock-DLL to start
string bevestiging;
char chatname[100];
char bericht[250];
char sbericht[250];
string strbericht;
string strsbericht;
long antwoord;
//here the Winsock-DLL will be started with WSAStartup
//version of the DLL
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
antwoord = WSAStartup(DLLVERSION, &wsaData);
if(antwoord != 0)
{
exit(1);
}
else
{
cout << "WSA started successfully" <<endl;
cout << "The status: \n" << wsaData.szSystemStatus <<endl;
}
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
SOCKET sConnect;
sConnect = socket(AF_INET, SOCK_STREAM, NULL);
if (sConnect == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
}
else
{
cout << "socket() is OK!\n" <<endl;
}
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(4444);
cout << "What is your chat name?" <<endl;
cin.getline(chatname, 100);
cout << "Do you want to connect to the server? [Y/N]" <<endl;
cin >> bevestiging;
if (bevestiging == "N")
{
exit(1);
}
else
{
if(bevestiging == "Y")
{
connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
antwoord = recv(sConnect, bericht, sizeof(bericht), NULL);
strbericht = bericht;
cout << strbericht << chatname <<endl;
while(true)
{
if(antwoord > 1)
{
cin.clear();
cin.sync();
cout << chatname << " :" <<endl;
cin.getline(sbericht, sizeof(sbericht));
antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = send(sConnect, chatname, sizeof(chatname), NULL);
while(antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL) && (antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL)))
{
antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = recv(sConnect, chatname, sizeof(chatname), NULL);
cout << chatname << ":" <<endl;
cout << sbericht <<endl;
cin.getline(sbericht, 250);
}
}
else
{
cout << "The connection to the server has been lost... \n" << "please exit the client." <<endl;
}
}
Sorry if I didn't write it well (I'm just learning to program sockets) but I can't figure this one out. So don't be hard on me, I still need to learn but cant find the things I need. So I think if somebody can show me how to do it, I can see it how its done and why.
Always learn something(I'm currently also busy with beejee's network programming tutorial).

sbericht and chatname - global variables
Your 2 threads working with this global buffers at the same time
So one thread rewrites data of another thread

There are a few issues with this code but sockets are a sticky thing to wrap your head around when you start. It seems in your server code that multithreading is your real beast. Note that threads and sockets are very different concepts but they are often used together. A large issue (as Andrew said) is that you have race conditions. You need to use mutexes to ensure mutual exclusion if you are writing to your global variables across multiple threads. For instance, in SocketHandler you need to protect your variable antwoord. Furthermore, use new and delete in C++ rather than malloc() and free() (these are used in C). Also, notice that for every new connection you overwrite the value of your csock variable. You need separate variables to hold each client's open connection socket.
Server sockets basically work in this manner: socket(), bind(), listen(), accept(). Now, in order to keep the port you are bind()'ed to and are listen()'ing on open for more connections, accept() reroutes your client and puts them on another socket file descriptor (which is the return value of accept()) so that you can continue to communicate with this client. Therefore, for each client, you need to hold the value of accept() uniquely.
I am skeptical, however, that in your client code, you are receiving what you expect. Does your protocol somewhere guarantee it will send just the username and then the chatname? You may simply need a single recv() call to retrieve all your data. Also, what is the relevance of the following line?
while(antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL) && (antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL)))
You are simply doing the same work twice - one time should be sufficient (and perhaps the program may block at this point and overwrite data without you knowing). For a simple text protocol, it is very likely that you can create a variable ~512bytes and receive all the information from the server appropriately in a single call to recv().
I tried to pick out the large issues in your code, and these problems are, more or less, frequent in other areas of your code too. If you are not familiar with multithreading, attack that problem later. Learn how to do single-threaded sockets, then go and learn multithreading. Tackling them both at once is going to bite you. Good luck!

Related

App stucks in accept() when LAN interfaces changed

I created a small app on small router with 4 LAN ports. Router has been flashed with OpenWrt system, Linux kernel 5.4.154
Devices connected to LAN ports are sending date over TCP POSTs. The app is listening on specified TCP port and sends data to the server or stores it in SD card. Everything work fine until someone will start playing with plugs on the LAN side. Somethings is happening and app hangs in accept() function waiting for incomming data.
I assume (please correct me if I'm wrong) system changes?/resets? port routing and data are not delivered to the app socket any more.
Is there a simple solution to keep the 'subscription' of TCP port?
I've tried to rewrite app in async mode, but not everything is working correctly, is this the only solution for this problem?
Below simpyfied working(!) code in blocking mode (I removed all unnecesary stuff, so it may not compile)
int main() {
// Create server_socket as socket
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
cerr << "Can't create a socket! Quitting" << endl;
}
int enable = 1;
if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
{
cout << GetTime() << "Can't use SO_REUSEADDR" << endl;
}
while (true) {
// Bind the ip address and port to a socket
listenningport = 55555;
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(listenningport);
inet_pton(AF_INET, "0.0.0.0", &hint.sin_addr);
if (bind(server_socket, (sockaddr*) &hint, sizeof(hint)) == -1) {
cerr << "Can't bind to IP/port" << endl;
}
// Tell Winsock the socket is for server_socket
if (listen(server_socket, SOMAXCONN) == -1) // handle multiconnections SOMAXCONN(4096, queue)
{
cerr << "Can't listen!" << endl;
}
// Wait for a connection
sockaddr_in client;
socklen_t clientSize = sizeof(client);
while (true) {
// Waiting for data on socket; block mode
int clientSocket = accept(server_socket, (sockaddr*) &client, &clientSize);
if (clientSocket == -1) {
cerr << "Problem with client connecting!" << endl;
// break the loop and try to renew socket connection
break;
}
else {
// receive all data till the end of message
int bytesReceived = 0;
while ((bytesReceived = recv(readSocket, out_data + msgSize, maxSizeOutData - msgSize - 1, 0)) > 0) {
msgSize += bytesReceived;
if (msgSize > maxSizeOutData + 1)
break;
}
// no data received
if (bytesReceived == -1) {
cerr << "Error in recv(). BytesReceived = -1" << endl;
}
close(clientSocket);
}
}
}

Winsock connect() hanging on one network, but not another

I am having trouble using the connect() function. My code was completely working before, but now I have moved to a different physical network and my blocking call to connect() no longer works, and just seems to hang indefinitely. Receiving broadcasts over UDP still works fine. Going back to the old network it works fine again. I cant for the life of me figure out why it works on one network and not the other. I have checked firewall settings and they are correct. What could be going on?
I have a pre-defined port being used and I am getting the address from the broadcast. I use recievefrom to receive the broadcast and set the outgoing ip address from it
ret = recvfrom (bcast, bcast_read,sizeof(j4cDAC_broadcast),0,(sockaddr*)&from,&size);
to.sin_addr = from.sin_addr;
local.sin_addr.s_addr = inet_addr("0.0.0.0");
Then for the TCP connection I have
dac = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// cout << "SOCKET\n";
if (dac == INVALID_SOCKET)
{
SetConsoleTextAttribute(console,(WORD)12);
cout << "TCP socket failed: " << WSAGetLastError();
connected_ = false;
return(1);
}
//set SO_REUSEADDR on a socket to true (1):
bool optval = true;
setsockopt(dac, SOL_SOCKET,SO_DONTLINGER,(const char*)&optval, sizeof(optval));
int pies = setsockopt(dac, SOL_SOCKET,SO_REUSEADDR,(const char*)&optval, sizeof(optval) );
if (pies == SOCKET_ERROR )
{
SetConsoleTextAttribute(console,(WORD)12);
cout << "SETSOCKOPT ERROR: " << WSAGetLastError() << endl;
} // */
local_T = local;
local_T.sin_port = htons ((short)TCPport);
//bind the tcp socket
bndt = bind(dac,(SOCKADDR*) &local_T,sizeof(local_T) );
if (bndt == SOCKET_ERROR )
{
SetConsoleTextAttribute(console,(WORD)12);
cout << "BIND TCP FAILED: " << WSAGetLastError();
if (WSAGetLastError() == WSAEACCES)
cout << "ACCESS DENIED";
cout << endl;
SetConsoleTextAttribute(console,(WORD)7);
shutdown(dac,2);
closesocket(dac);
connected_ = false;
return 1;
}
c = connect(dac, (sockaddr*) &to, size); // <------- This hangs
if (c == SOCKET_ERROR)
{
cout << "connection problem: " << WSAGetLastError() <<endl;
}
connected_ = true;`
I found this to be an issue with VMWare virtual networking devices. Even though I had no virtual machines running, after much testing of various things, I found the device broadcast was being received on one of the virtual networking interfaces from VMWare somehow. Disabling these two devices has fixed this issue.

c++ server client chat

I'm making a server, client app in c++ console based.
What I did so far:
I can connect to the server.
I can send messages to the server.
The server can send the messages back.
But what I can't figure out, how can I let the server act also as a client to send messages to the client while he is processing received messages from the client?
People can use it as an example as well :D
Well I will post also some parts of the code:
server:
#include "stdafx.h"
using namespace std;
//our main function
void main()
{
int numClients;
long antwoord;
char chatname[100];
char bericht[250]; //messages
char sbericht[250]; //smessages
//here we set the Winsock-DLL to start
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
//here the Winsock-DLL will be started with WSAStartup
//version of the DLL
antwoord = WSAStartup(DLLVERSION, &wsaData);
if(antwoord != 0)
{
WSACleanup();
exit(1);
}
else
{
cout << "WSA started successfully" <<endl;
cout << "The status: \n" << wsaData.szSystemStatus <<endl;
}
//the DLL is started
//structure of our socket is being created
SOCKADDR_IN addr;
//addr is our struct
int addrlen = sizeof(addr);
//socket sListen - will listen to incoming connections
SOCKET sListen;
//socket sConnect - will be operating if a connection is found.
SOCKET sConnect;
//setup of our sockets
//opgezocht op internet - AF_INET bekend dat het lid is van de internet familie
//Sock_STREAM betekenend dat onze socket een verbinding georiƫnteerde socket is.
sConnect = socket(AF_INET,SOCK_STREAM,NULL);
//now we have setup our struct
//inet_addr is our IP adres of our socket(it will be the localhost ip
//that will be 127.0.0.1
addr.sin_addr.s_addr = inet_addr("192.168.1.103");
//retype of the family
addr.sin_family = AF_INET;
//now the server has the ip(127.0.0.1)
//and the port number (4444)
addr.sin_port = htons(4444);
//here we will define the setup for the sListen-socket
sListen = socket(AF_INET,SOCK_STREAM,NULL);
if (sConnect == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
WSACleanup();
}
else
{
cout << "Connect socket() is OK!" <<endl;
}
if(sListen == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
WSACleanup();
}
else
{
cout << "Listen socket() is OK!" <<endl;
}
//here the sListen-socket will be bind
//we say that the socket has the IP adress of (127.0.0.1) and is on port (4444)
//we let the socket become the struct "addr"
if(bind(sListen, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR)
{
cout << "bind() failed: \n" << WSAGetLastError() <<endl;
WSACleanup();
exit(1);
}
else{
cout << "bind() is OK!" <<endl;
}
//here we will tell what the server must do when a connection is found
//therefor we will create an endless loop
cout << "Waiting for a incoming connection..." <<endl;
for(;;)
{
//now we let the socket listen for incoming connections
//SOMAXCOMM heeft het nut dat het dan voordurend luisterd naar inkomende verbindingen zonder limiet
listen(sListen, SOMAXCONN);
while(numClients < SOMAXCONN)
{
//if a connection is found: show the message!
if(sConnect = accept(sListen, (SOCKADDR*)&addr, &addrlen))
{
cout << "A Connection was found!" <<endl;
antwoord = send(sConnect, "Welcome to our chat:", 21,NULL);
if(antwoord > 1)
{
antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = recv(sConnect, chatname, sizeof(chatname), NULL);
while(antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL) && (antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL)) )
{
antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = send(sConnect, chatname, sizeof(chatname), NULL);
}
}
else
{
cout << "The connection to the client has been lost... \n" << "please exit the server." <<endl;
break;
}
numClients++;
}
}
}
}
Client:
// ChatServer.cpp : Defines the entry point for the console application.
//
//include of the stdafx.h file where importent files are being included
#include "stdafx.h"
using namespace std;
void smessage()
{
}
//our main function
int main()
{
//here we set the Winsock-DLL to start
string bevestiging;
char chatname[100];
char bericht[250];
char sbericht[250];
string strbericht;
string strsbericht;
long antwoord;
//here the Winsock-DLL will be started with WSAStartup
//version of the DLL
WSAData wsaData;
WORD DLLVERSION;
DLLVERSION = MAKEWORD(2,1);
antwoord = WSAStartup(DLLVERSION, &wsaData);
if(antwoord != 0)
{
exit(1);
}
else
{
cout << "WSA started successfully" <<endl;
cout << "The status: \n" << wsaData.szSystemStatus <<endl;
}
SOCKADDR_IN addr;
int addrlen = sizeof(addr);
SOCKET sConnect;
sConnect = socket(AF_INET, SOCK_STREAM, NULL);
if (sConnect == INVALID_SOCKET)
{
cout << "Error at socket(): \n" << WSAGetLastError() <<endl;
}
else
{
cout << "socket() is OK!\n" <<endl;
}
addr.sin_addr.s_addr = inet_addr("192.168.1.103");
addr.sin_family = AF_INET;
addr.sin_port = htons(4444);
cout << "What is your chat name?" <<endl;
cin.getline(chatname, 100);
cout << "Do you want to connect to the server? [Y/N]" <<endl;
cin >> bevestiging;
if (bevestiging == "N")
{
exit(1);
}
else
{
if(bevestiging == "Y")
{
connect(sConnect, (SOCKADDR*)&addr, sizeof(addr));
antwoord = recv(sConnect, bericht, sizeof(bericht), NULL);
strbericht = bericht;
cout << strbericht << chatname <<endl;
while(true)
{
if(antwoord > 1)
{
cin.clear();
cin.sync();
cout << chatname << " :" <<endl;
cin.getline(sbericht, 250);
antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = send(sConnect, chatname, sizeof(chatname), NULL);
while(antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL) && (antwoord = send(sConnect, sbericht, sizeof(sbericht), NULL)))
{
antwoord = recv(sConnect, sbericht, sizeof(sbericht), NULL);
antwoord = recv(sConnect, chatname, sizeof(chatname), NULL);
cout << chatname << ":" <<endl;
cout << sbericht <<endl;
cin.getline(sbericht, 250);
}
}
else
{
cout << "The connection to the server has been lost... \n" << "please exit the client." <<endl;
}
}
}
}
}
You would probably have to open another socket. The client would have to act as a server as well.
First of all: putting a 20mb zip file in to the web for about 4 interesting source files is not a good option. Your object files and debug output is of no interest to us, since we want to help with your source code. Try uploading a zip file containing only the source files the next time.
Secondly: If others want to understand your source code and are not familiar with your native language, they have to guess. Try using english as source code language for this and a variety of other reasons.
Now to answer your question:
The answer is already in your code. Currently, the server is looping until a maximum number of connects, receives input and sends back an answer. So actually you have already implemented it. I guess if you want to send initiated messages in both ways you have to alter your software architecture a bit.
Your code has a few fundamental problems:
The server can only handle one client at a time. If your server will ever have more than a single user on it (as a chat server invariably will), you need to be able to listen for more than one connection at once. select, or WSAEventSelect and WaitForMultipleObjects, would help a lot here.
You assume that a whole fixed-size message will appear at a time. TCP can not guarantee that (as the "stream" concept considers the data as just a potentially infinite sequence of individual bytes), and a half-sent message could freeze up your server while it waits for the rest. Not a big deal if this is all on your LAN, but if you expose this service to the internet, you're asking for random lockups. In order to prevent that, get the data and put it in a buffer as it comes, processing it only when you have a whole message.
The conversation is done in lock-step. That is, the client sends a message, and waits for a response, and then (and only then) expects console input. With this design, there will always be one message received per message sent. In order to get around this, i'll often have a thread for the data going in each direction -- one that gets the console input and sends it to the server, while the other listens to the server and prints the message received. (Note, this means messages could be received while you're typing. That's kinda the point. But it makes console input a bit annoying.) Threading is a semi-advanced topic -- once you start creating new threads, you often have to worry about synchronization and such. But it's generally cleaner than the alternatives in this case.
Sample threaded code (very roughly, since i don't have a C++ compiler handy):
const int MessageLength = 250;
const int NameLength = 250;
char myname[NameLength];
bool sendFully(SOCKET s, char* buffer, size_t buffer_len, int flags)
{
char *end = buffer + buffer_len;
while (buffer != buffer_len)
{
int sent = send(s, buffer, end - buffer, flags);
if (sent == 0) return false;
buffer += sent;
}
return true;
}
DWORD WINAPI watchConsoleInput(void*)
{
char input[MessageLength];
while (true)
{
std::cin.getline(input, MessageLength);
if (!sendFully(sConnect, input, sizeof(input), 0))
break;
if (!sendFully(sConnect, myname, sizeof(myname), 0))
break;
}
return 0;
}
int main()
{
char chatname[NameLength];
char sbericht[MessageLength];
... get our name in myname ...
... do the connect stuff ...
HANDLE watcher = CreateThread(NULL, 0, watchConsoleInput, NULL, 0, NULL);
while (true)
{
// Added MSG_WAITALL to work around the whole-message-at-a-time thing
if (recv(sConnect, sbericht, sizeof(sbericht), MSG_WAITALL) != sizeof(sbericht))
break;
if (recv(sConnect, chatname, sizeof(chatname), MSG_WAITALL) != sizeof(sbericht))
break;
}
// Don't care about errors; we're just being polite
shutdown(sConnect, SD_BOTH);
closesocket(sConnect);
cout << "Connection lost\n";
// ExitProcess rather than just 'return', so we know the watcher thread dies
ExitProcess(0);
}

EAGAIN on recv()

I implented a socket client to communicate to an ip camera with RTSP over HTTP to get teh video from the camera.
To stablished the communication with the camera, first i have to set an HTTP-GET tunnel, then send the RTSP commands. When the camera loses the connection, the program has to close the tunnel handler, finish the thread and when the process return to the main function, it begins the communication (start the treads, and so on).
On the reconnection: the http-get tunnel is set ok, i mean, the socket connects and receives a "HTTP OK", so the program sends a RTSP "DESCRIBE" but the recv always return an EAGAIN error. I check with wireshar that the DESCRIBE OK response is sent from the camera, but the recv never gets it.
Here is the code:
struct sockaddr_in aServer;
// string myData;
char *myData=new char [256];
connection *c=(connection*)vargp;
memset(&aServer, 0, sizeof aServer);
aServer.sin_family = AF_INET;
aServer.sin_addr.s_addr = inet_addr(c->theServer.c_str());
if (aServer.sin_addr.s_addr == INADDR_NONE)
{
struct hostent *hp;
hp = gethostbyname(c->theServer.c_str());
if (hp != NULL)
{
memcpy(&aServer.sin_addr, hp->h_addr, hp->h_length);
aServer.sin_family = hp->h_addrtype; //Protocol family
}
else
cout << "Failed to resolve " << c->theServer.c_str() << ": " << hstrerror(h_errno) << endl;
}
aServer.sin_port = htons(c->thePort);
c->fd_get = socket(AF_INET, SOCK_STREAM, 0);
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(c->fd_get, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
if (c->fd_get < 0){
cout << "fd_get < 0" << endl;
c->bFin=true;
c->WakeUP();
}
if (connect(c->fd_get, (struct sockaddr *) &aServer, sizeof aServer) < 0){
cout << "connect fd_get < 0" << endl;
c->bFin=true;
c->WakeUP();
}
if(!c->bFin){
sprintf(myData, "GET %s HTTP/1.1\r\n", c->theURI.c_str());
sprintf(myData, "%sx-sessioncookie: %s\r\nAccept: application/x-rtsp-tunnelled\r\nAuthorization: %s\r\n\r\n", myData,c->theHTTPSessionId.c_str(), c->addAuthorization(c->aGlobalUsername, c->aGlobalPassword).c_str() );
cout << myData << endl;
write(c->fd_get, myData, strlen(myData));
//LISTENING...
int theLen=1500; //3000;
int ret=0;
unsigned char datosRecibidos[3000];
int flags =fctl(c->fd_get, F_GETFD;
if((flags & O_NONBLOCK) == O_NONBLOCK){
fprint(stderr, "yup, its nonblocking");
}
else{
fprint(stderr, "nope, its blocking");
}
while (c->bFin==false){
ret = read(c->fd_get, ReceivedData, theLen);
// ret= recvfrom(c->fd_get, ReceivedData, theLen, 0, (struct sockaddr *) 0, (socklen_t*)0);
if (ret == 0)
{
cout << "Server closed connection: 0" << endl;
}
else
if (ret == -1){
fprintf (stderr, "\n[%d]: %s %d\n", __LINE__, strerror (errno), errno);
if(errno==107 ||errno==EAGAIN){
cout << "errno" << endl;
c->bFin=true;
c->WakeUP();
cout << "vuelta wakeUP" << endl;
break;// empezar de nuevo
}else{
cout << "errno" << endl;
}
}
else{
//cout << (string)ReceivedData[0]<< endl;
c->ProcessReceivedData(ReceivedData, ret);
usleep(10);
}
}
close(c->fd_get);
c->fd_get = -1;
}
Could it be a timeout problem? or a stack problem? How can i solve it?
Thanks in advance for your help. Best regards.
cristina
EAGAIN means there is no data available for reading on a non-blocking socket. So, you should run the recv call again.
You haven't actually posted enough code to suggest there is a programming fault, although can I ask if when you detect the connection is closed that you also close down your end as well before re-establishing everything?
Is your socket open in O_NONBLOCK mode? You can check like this:
int flags = fcntl(fd, F_GETFD);
if ((flags & O_NONBLOCK) == O_NONBLOCK) {
fprintf(stderr, "Yup, it's nonblocking");
}
else {
fprintf(stderr, "Nope, it's blocking.");
}
In nonblocking mode, recv will return immediately with errno set to EAGAIN if there is nothing to receive yet.
I would always use poll() or select() before going for each socket read operation.
Also to test for NON-Blocking:
int flags = fcntl(fd, F_GETFL, 0);
if (flags & O_NONBLOCK) {
fprintf(stderr, "Yup, it's nonblocking");
} else {
fprintf(stderr, "Nope, it's blocking.");
}

C++ strange socket data

Hey guys, here is my code.
int main() {
char buffer[BUFSIZE];
// define our address structure, stores our port
// and our ip address, and the socket type, etc..
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;
// create our socket.
int sock;
if ( (sock = socket(addrinfo.sin_family, SOCK_STREAM, 0)) < 0) {
cout << "Error in creating the socket.";
}
// bind our socket to the actual adress we want
if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) {
cout << "Error in binding.";
}
// open the socket up for listening
if (listen(sock, 5) != 0) {
cout << "Error in opening listener.";
}
cout << "Waiting for connections...." << endl;
char *msg = "Success! You are connected.\r\n";
// continuously accept new connections.. but no multithreading.. yet
while(1) {
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);
if(int client = accept(sock, (struct sockaddr*)&client_addr, &sin_size)) {
cout << "Recived new connection from " << inet_ntoa(client_addr.sin_addr) << endl;
send(client, msg, strlen(msg), 0);
while(1) {
send(client, buffer, recv(client, buffer, BUFSIZE, 0), 0);
cout << buffer << endl;
strcpy(buffer, "");
}
} else {
cout << "Error in accepting new connection." << endl;
}
}
close(sock);
return 0;
}
Now, I'm very new to sockets, Im just sort of trying to get a feel for them but I do have some experience with sockets in PHP. I'm using telnet via putty on my linux machine to test this, I don't know if thats causing any issues but the server is outputting some strange characters and I don't know why. I think it has something to do with the buffer, but I'm not really sure. I can send things like "hi" to the server via telnet and it outputs them just fine and sends them back to me but when I send things like "hoobla" it starts the funky character stuff. Any suggestions would be helpful!
Thanks in advance!
You're getting rubbish printed out because recv does not null-terminate your buffer.
The important section in the below code is:
int num = recv(client,buffer,BUFSIZE,0);
if (num < 1) break;
send(client, ">> ", 3, 0); // <<-- Nice to have.
send(client, buffer, num, 0);
buffer[num] = '\0'; // <<-- Really important bit!
if (buffer[num-1] == '\n') // <<-- Nice to have.
buffer[num-1] = '\0'; // <<-- Nice to have.
cout << buffer << endl;
which will properly terminate your buffer before trying to print it, as well as remove the trailing newline if present (and allow the client to distinguish between input and echoed lines).
This one (a complete program) works a little better:
using namespace std;
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#define BUFSIZE 1000
#define PORT 1234
int main() {
char buffer[BUFSIZE];
// define our address structure, stores our port
// and our ip address, and the socket type, etc..
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;
// create our socket.
int sock;
if ( (sock = socket(addrinfo.sin_family, SOCK_STREAM, 0)) < 0) {
cout << "Error in creating the socket.";
return -1;
}
// bind our socket to the actual adress we want
if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) {
cout << "Error in binding.";
return -1;
}
// open the socket up for listening
if (listen(sock, 5) != 0) {
cout << "Error in opening listener.";
return -1;
}
char *msg = "Success! You are connected.\r\n";
// continuously accept new connections.. but no multithreading.. yet
while(1) {
cout << "Waiting for connections...." << endl;
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);
if(int client =
accept(sock, (struct sockaddr*)&client_addr, &sin_size))
{
cout << "Recieved new connection from "
<< inet_ntoa(client_addr.sin_addr) << endl;
send(client, msg, strlen(msg), 0);
while(1) {
int num = recv(client,buffer,BUFSIZE,0);
if (num < 1) break;
send(client, ">> ", 3, 0);
send(client, buffer, num, 0);
buffer[num] = '\0';
if (buffer[num-1] == '\n')
buffer[num-1] = '\0';
cout << buffer << endl;
strcpy(buffer, "");
}
} else {
cout << "Error in accepting new connection." << endl;
}
}
close(sock);
return 0;
}
On the client side:
$ telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Success! You are connected.
hello
>> hello
my name is pax
>> my name is pax
and you?
>> and you?
<CTRL-D>
Connection closed by foreign host.
and, on the server side:
$ ./testprog
Waiting for connections....
Recived new connection from 127.0.0.1
hello
my name is pax
and you?
Waiting for connections....
The problem is that buffer is not guaranteed to contain a string-terminating null character. Add the line buffer[BUFSIZE-1] = '\0' just before your cout << buffer.
Even better, actually record how many bytes were received, and use that information to determine if you overran your buffer.