So I have an issue trying to iterate through my container in c++ with visual studio Community 2015.
I'm trying to write a server/client on windows using select() and I get the error:
vector iterator not incrementable
I'm not calling a vector::erase() or such, although I do use a vector::push_back()
void MGKServer::mainLoop()
{
MGKServerSocket *mgk;
std::vector<User *> users;
int actual = 0;
char buffer[1024];
mgk = new WindowsServerSocket();
mgk->init("127.0.0.1", 4242, "TCP");
int sock = mgk->getSock();
std::cout << "sock is: " << mgk->getSock() << std::endl;
while (1)
{
this->setFd(sock, &users); // FD_ZERO(&_readfd) and FD_SET for each user's socket and the server socket
std::cout << "there is currently " << users.size() << " user(s) connected" << std::endl;
if (select(FD_SETSIZE + 1, &this->_readfd, NULL, NULL, NULL) == -1)
exit(errno);
// When a user connects
if (FD_ISSET(sock, &this->_readfd))
{
// addNewUser creates a pointer to an object User , set his socket to the given one and push it in the vector
if (this->addNewUser(sock, &users) == -1)
std::cout << "Can't add newUser" << std::endl;
}
// When a user sends a message to the server
else
{
int debug = 0;
std::vector<User *>::iterator it = users.begin();
while (it != users.end())
{
if (it == users.end())
std::cout << "Test if something went wrong with iterations" << std::endl;
if (FD_ISSET((*it)->getSocket(), &this->_readfd))
{
// RecvUser will just call recv with the client socket and store the message in buffer.
int c = mgk->recvUser((*it)->getSocket(), buffer);
// Means the user disconnected so i close his socket
if (c == 0)
{
std::cout << "user with socket: " << (*it)->getSocket() << "disconnected" << std::endl;
closesocket((*it)->getSocket());
}
// Means he sends an instruction
else
std::cout << "ok" << std::endl;
}
std::cout << "Debug = " << debug << std::endl;
++debug;
it++; // <- This small line seems to be the problem
}
std::cout << "Out of For loop" << std::endl;
}
std::cout << "found something on socket" << std::endl;
}
}
here is what i do in addNewUser:
int MGKServer::addNewUser(int socket, std::vector<User *> *users)
{
std::cout << "----NEW USER----" << std::endl;
SOCKADDR_IN usin = { 0 };
User *u;
int size;
int usock;
size = sizeof(usin);
std::cout << "New user is trying to connect, socket is: ";
usock = accept(socket, (SOCKADDR *)&usin, &size);
if (usock == SOCKET_ERROR)
{
std::cout << "socket error occured" << std::endl;
return (-1);
}
std::cout << usock << std::endl;
FD_SET(usock, &this->_readfd);
u = new User();
u->setSocket(usock);
users->push_back(u);
return (0);
}
My object User only contains a socket with get&set methods for now.
My MGKServerSocket is just an abstration for windows/linux socket. It contain basic function for initializing my socket and send & recv data to users.
So at first I had a list container but I've got the same error. So I switched to try with vector instead but nothing changed.
In the beginning, I also used a for loop instead of my current while loop but, once again, nothing changed.
I know that there's already many questions for this error, but they usually use erase, insert inside the for loop or create the iterator when the list is empty which I don't. So my question is, why do I get this error ?
Related
Another try with getting parallel processes to work. Please excuse the amount of code but every attempt to shorten it makes the error vanish.
What I tested so far:
sending int from parent to child, from child to parent, and from parent to child and then back: works
processing a list of int: send from parent to child, modify and back to parent: works
more data: int + string, from parent to child, modify and back to parent: works
a list of data the same way: works
But when I run the same function that works a second time it always fail.
This is the function that creates the child process:
//parent sends binary data from list to child which sends back modified data
bool processParallel6(std::vector<std::pair<int, std::string>> & data)
{
//define pipe
int parent2Child[2];
int child2Parent[2];
//create pipe
pipe(parent2Child);
pipe(child2Parent);
//fork
pid_t child = fork();
if(child == 0) //child process
{
//close not needed end of pipe
close(parent2Child[1]);
close(child2Parent[0]);
for(;;)
{
struct pollfd pfd;
pfd.fd = parent2Child[0];
pfd.events = POLLIN;
//wait until data is available at the pipe
cout << "c: poll ..." << endl;
if(poll(&pfd, 1, -1) < 0)
{
cout << "c: poll: " << strerror(errno) << endl;
exit(-1);
}
cout << "c: poll says there are data" << endl;
if((pfd.revents&POLLIN) == POLLIN)
{
int data;
std::string text;
if(!readData3(parent2Child[0], data, text))
exit(-2);
cout << "c: data received: " << data << " " << text << endl;
if(data == -1)
break;
if(!writeData3(child2Parent[1], data * 2, text + text))
exit(-3);
cout << "c: sent data to parent: " << 2 * data << " " << text + text << endl;
}
}
close(parent2Child[0]);
close(child2Parent[1]);
exit(0);
}
else //parent process
{
//close not needed end of pipe
close(parent2Child[0]);
close(child2Parent[1]);
//send data to child
if(!writeData3(parent2Child[1], data.back().first, data.back().second))
return false;
cout << "p: wrote data: " << data.back().first << " " << data.back().second << endl;
data.pop_back();
//read result from child
for(;;)
{
struct pollfd pfd;
pfd.fd = child2Parent[0];
pfd.events = POLLIN;
//wait until data is available at the pipe
cout << "p: poll ..." << endl;
if(poll(&pfd, 1, -1) < 0)
{
cout << "p poll: " << strerror(errno) << endl;
return false;
}
cout << "p: poll says there are data" << endl;
if((pfd.revents&POLLIN) == POLLIN)
{
int data;
std::string text;
if(!readData3(child2Parent[0], data, text))
return false;
cout << "p: data received: " << data << " " << text << endl;
}
if(data.empty())
break;
if(!writeData3(parent2Child[1], data.back().first, data.back().second))
return false;
cout << "p: wrote data: " << data.back().first << " " << data.back().second << endl;
data.pop_back();
}
//send stop data
if(!writeData3(parent2Child[1], -1, "notext"))
return false;
cout << "p: sent stop data " << endl;
//wait for child to end
wait(nullptr);
//close all pipes
close(parent2Child[1]);
close(child2Parent[0]);
}
return true;
}
For reading and writing data I use this two functions:
bool readData3(int fd, int & number, std::string & text)
{
char numberBuf[sizeof(int)];
int bytesRead = read(fd, numberBuf, sizeof(int));
if(bytesRead > 0)
{
number = *(int *)numberBuf;
}
else if(bytesRead < 0)
{
cout << "readData3: " << strerror(errno) << endl;
return false;
}
char sizeBuf[sizeof(int)];
int size = -1;
bytesRead = read(fd, sizeBuf, sizeof(int));
if(bytesRead > 0)
{
size = *(int *)sizeBuf;
}
else if(bytesRead < 0)
{
cout << "readData3: " << strerror(errno) << endl;
return false;
}
char textBuf[size];
bytesRead = read(fd, textBuf, size);
if(bytesRead > 0)
{
text = std::string(textBuf);
}
else if(bytesRead < 0)
{
cout << "readData3: " << strerror(errno) << endl;
return false;
}
return true;
}
bool writeData3(int fd, const int number, const std::string text)
{
int bytesWritten = write(fd, &number, sizeof(int));
if(bytesWritten < 0)
{
cout << "writeData3: " << strerror(errno) << endl;
return false;
}
int size = text.size() + 1;
bytesWritten = write(fd, &size, sizeof(int));
if(bytesWritten < 0)
{
cout << "writeData3: " << strerror(errno) << endl;
return false;
}
bytesWritten = write(fd, text.c_str(), size);
if(bytesWritten < 0)
{
cout << "writeData3: " << strerror(errno) << endl;
return false;
}
return true;
}
Finally I run it like this:
#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <bitset>
#include <memory>
#include <poll.h>
#include <cstring>
using namespace std;
int main(int /*argc*/, char* /*argv*/[])
{
std::vector<std::pair<int, std::string>> data;
data.push_back(std::make_pair(1, "one"));
data.push_back(std::make_pair(2, "two"));
cout << "6a ########################################################" << endl << flush;
processParallel6(data);
cout << "6b ########################################################" << endl << flush;
processParallel6(data);
return 0;
}
This is the output:
6a ###############################################
p: wrote data: 2 two
p: poll ...
c: poll ...
c: poll says there are data
c: data received: 2 two
p: poll says there are data
p: data received: 4 twotwo
p: wrote data: 1 one
p: poll ...
c: sent data to parent: 4 twotwo
c: poll ...
c: poll says there are data
c: data received: 1 one
p: poll says there are data
p: data received: 2 oneone
p: sent stop data
c: sent data to parent: 2 oneone
c: poll ...
c: poll says there are data
c: data received: -1 notext
6b ###################################################
c: poll ...
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid
c: poll says there are data
c: poll ...
c: poll says there are data
c: poll ...
The last 4 lines are repeated a thousands of times. This output comes most of the times, but sometimes I have seen a std::bad_alloc error. When I try strace it crashes too, but when it runs I have seen directly after the second run of processParallel6() a line with mmap, ENOEM and 'Cannot allocate memory'
What happens here? Why is it working the first time, but not the second time?
You attempting to copy an invalid std::string reference.
std::terminate is getting called in the constructor of std::string. The constructor is implicitly called in processParallel6 when calling writeData3:
bool writeData3(int fd, const int number, const std::string text)
...
//send data to child
if(!writeData3(parent2Child[1], data.back().first, data.back().second))
return false;
You are expecting that data.back().second is a valid string reference, but nothing in the code ensures that is the case.
You construct data and place two entries in it:
data.push_back(std::make_pair(1, "one"));
data.push_back(std::make_pair(2, "two"));
In the first call to processParallel6 you run the following block of code twice:
if(!writeData3(parent2Child[1], data.back().first, data.back().second))
return false;
cout << "p: wrote data: " << data.back().first << " " << data.back().second << endl;
data.pop_back();
At this point data is empty. You cannot make another call to processParallel6 because it expects that data contains at least one element.
I have a server in a raspberry pi, and want to allow multithreading. The server is working. The client is in windows.
I believe I need to send the socket id through the pthread_create, but haven't found how. Is there anything else I need to send?
What is the best way to do it?
I've searched the internet, stackoverflow included, and tryed some resolutions, but they didn't work.
const int PORT = 12000;
TCPServer tcp;
pthread_t my_thread[MAXCLIENTQUEUE];
int clientID = 0;
int main()
{
tcp.setup(PORT);
int clientQueueSize = 0, threadJoin = 0;
void *res;
do {
socklen_t sosize = sizeof(tcp.clientAddress);
//realizar o accept
tcp.newsockfd[clientQueueSize] = accept(tcp.sockfd, (struct sockaddr*) & tcp.clientAddress, &sosize);
if (tcp.newsockfd[clientQueueSize] == -1)
{
cout << "Error accepting -> " << tcp.newsockfd[clientQueueSize] << endl;
tcp.detach();
}
cout << ">- accept: " << strerror(errno) << " / codigo: " << tcp.newsockfd[clientQueueSize] << " - Endereco: " << inet_ntoa(tcp.clientAddress.sin_addr) << endl;
clientID++;
cout << ">>> client accepted" << " | Client ID: " << clientID << endl;
// criar threads
int ret = pthread_create(&my_thread[clientQueueSize], NULL, messenger, &tcp.newsockfd[clientQueueSize]);
cout << ">- pthread: " << strerror(errno) << " / codigo: " << ret << endl;
if (ret != 0) {
cout << "Error: pthread_create() failed\n" << "thread_n " << my_thread[clientQueueSize] << endl;
exit(EXIT_FAILURE);
}
cout << "thread n " << my_thread[clientQueueSize] << endl;
clientQueueSize++;
}
while (clientQueueSize < MAXCLIENTQUEUE);
pthread_exit(NULL);
return 0;
}
The server accepts multiple connections but only sends messages to the first client, the others connected successfully, but never receive messages.
I want for the server to be able to send messages to all the clients.
You have to create threads for all sockets.
Or, use Windows-depended async select methods.
P.S. Forget pthreads and use the standard std::thread.
map<SOCKET,std::string> clients;
void newclient(SOCKET x)
{
for(;;)
{
int r = recv(x,...);
if (r == 0 || r == -1)
break;
}
// remove it from clients, ensure proper synchronization
}
void server()
{
SOCKET x = socket(...);
bind(x,...);
listen(x,...);
for(;;)
{
auto s = accept(x,...);
if (s == INVALID_SOCKET)
break;
// save to a map, for example, after ensuring sync with a mutex and a lock guard
m[s] = "some_id";
std::thread t(newclient,s);
s.detach();
}
}
int main() //
{
// WSAStartup and other init
std::thread t(server);
t.detach();
// Message Loop or other GUI
}
I need to receive a HTTP request from my browser, when I run localhost:8228 it works fine, I receive the header in the buffer and am able to write it to the console and even echo send it back to the browser. But when I try reading a request from a actual webpage, buffer is empty, it prints nothing.
I have a simple main that looks like this:
int main (int argc, char *argv[]) {
char buffer[1024*1024] = {0};
int port_number = 8228;
if (argc == 1)
std::cout << "Using default port number, 8228." << std::endl;
else if (argc == 3) {
port_number = atoi(argv[2]);
} else {
std::cout << "::Error::" << std::endl;
std::cout << "Wrong number of arguments." << std::endl;
exit[0];
}
AppSocket app;
app.Start((int)port_number);
app.AcceptCall();
int request_size = app.ReceiveRequest(buffer, sizeof(buffer));
return 0;
}
My AppSocket functions would be:
void AppSocket::Start(int port) {
// Create a socket
listening_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listening_fd == -1) {
std::cerr << "Could not create a socket." << std::endl;
exit(-1);
}
app_hint.sin_family = AF_INET;
app_hint.sin_port = htons(port);
inet_pton(AF_INET, "127.0.0.1", &app_hint.sin_addr);
if (bind(listening_fd, (sockaddr*)&app_hint, sizeof(app_hint))< 0) {
std::cerr << "Cannot bind to IP/port." << std::endl;
exit(-2);
}
std::cout << "Socket has been bound." << std::endl;
if (listen(listening_fd, SOMAXCONN) == -1) {
std::cerr << "Cannot listen." << std::endl;
exit(-3);
}
std::cout << "Listening to port " << port << std::endl;
std::cout << "Your socket is: " << listening_fd << std::endl;
}
void AppSocket::AcceptCall() {
client_size = sizeof(client_addr);
client_fd =
accept(listening_fd, (sockaddr *)&client_addr, &client_size);
if (client_fd < 0) {
std::cerr << "Error connecting to client." << std::endl;
exit(-4);
}
std::cout << inet_ntoa(client_addr.sin_addr)
<< " connected to port "
<< ntohs(client_addr.sin_port) << std::endl;
close(listening_fd);
}
int AppSocket::ReceiveRequest(char *buffer, int max) {
std::cout << "Client is: " << client_fd << std::endl;
memset(buffer, 0, buff_size); //clear buffer
int n = recv(client_fd, buffer, buff_size, 0);
if (n < 0)
std::cerr << "A connection issue has occured." << std::endl;
if (n == 0)
std::cout << "Client disconected." << std::endl;
std::cout << "recv return " << n << std::endl;
std::cout << buffer << std::endl;
return n;
}
When I run and access a webpage I get this:
Using default port number, 8228.
Socket has been bound.
Listening to port 8228
Your socket is: 3
127.0.0.1 connected to port 37522
Client is: 4
recv return 3
None of the questions I've read seem to work for me...
edit: sorry one of the lines in the main code wasn't copied.
How can I receive repeatedly? A while loop? I tried that and just kept receiving nothing.
The code works, what was happening is that the firefox proxy settings were wrong, when I ran localhosts it worked fine because it was actually working as the server due to the port it was using but when trying to access a "real" website it didn't. After configuring it correctly it did just what it's supposed to do.
I'm trying my hands at network programming for the first time, implementing a small IRC bot using the SFML network functionality.
The connection gets established, but from there on I can't do much else. Trying to receive any data from the server yields nothing, until I get the "Ping timeout" message after a few seconds.
Removing all or some of the receive() calls in the loginOnIRC function doesn't do any good.
Trying to connect via telnet with the exact same messages works. Here I get a PING message right after sending my NICK message.
Am I missing something?
My code is as follows
#include <iostream>
#include <string>
#include <SFML/Network.hpp>
#define ARRAY_LEN(x) (sizeof(x)/sizeof(*x))
void receive(sf::TcpSocket* sck)
{
char rcvData[100];
memset(rcvData, 0, ARRAY_LEN(rcvData));
std::size_t received;
if (sck->receive(rcvData, ARRAY_LEN(rcvData), received) != sf::Socket::Done)
{
std::cout << "oops" << std::endl;
}
std::cout << "Received " << received << " bytes" << std::endl;
std::cout << rcvData << std::endl;
}
int establishConnection(sf::TcpSocket* sck)
{
sf::Socket::Status status = sck->connect("irc.euirc.net", 6667, sf::seconds(5.0f));
if (status != sf::Socket::Done)
{
std::cout << "Error on connect!" << std::endl;
return 1;
}
std::cout << "Connect was successful!" << std::endl;
return 0;
}
int loginOnIRC(sf::TcpSocket* sck)
{
receive(sck); // We get a Ping timeout here
std::string data{ "NICK NimBot" };
if(sck->send(data.c_str(), data.length()) != sf::Socket::Done)
{
std::cout << "Error on sending " << data << std::endl;
return 1;
}
receive(sck);
data = "USER NimBot * * :Nimelrians Bot";
if (sck->send(data.c_str(), data.length()) != sf::Socket::Done)
{
std::cout << "Error on sending " << data << std::endl;
return 1;
}
receive(sck);
data = "JOIN #nimbottest";
if (sck->send(data.c_str(), data.length()) != sf::Socket::Done)
{
std::cout << "Error on sending " << data << std::endl;
return 1;
}
return 0;
}
int main()
{
sf::TcpSocket sck{};
establishConnection(&sck); // works
loginOnIRC(&sck);
while(true)
{
char data[100];
memset(data, 0, ARRAY_LEN(data));
std::size_t received;
sf::Socket::Status rcvStatus = sck.receive(data, ARRAY_LEN(data), received);
if (rcvStatus != sf::Socket::Done)
{
std::cout << "oops" << std::endl;
if (rcvStatus == sf::Socket::Disconnected)
{
break;
}
}
std::cout << "Received " << received << " bytes" << std::endl;
std::cout << data << std::endl;
}
return 0;
}
I'm trying to send a string via SocketSource and SocketSink. But somehow it won't work properly. I simply want to send it from my server to the client. Here's the code:
Server:
CryptoPP::Socket server;
CryptoPP::Socket client;
sockaddr_in client_sadr;
CryptoPP::socklen_t size_sock = sizeof(sockaddr_in);
timeval timev = {3, 0};
std::string test("a simple test");
CryptoPP::Socket::StartSockets();
server.Create(SOCK_STREAM);
server.Bind(4213, NULL);
server.Listen();
server.Accept(client, (sockaddr*)&client_sadr, &size_sock);
std::cout << "Client connected" << std::endl;
while (!client.SendReady(&timev));
CryptoPP::StringSource ss(test, true, new CryptoPP::SocketSink(client));
std::cout << "Data sent" << std::endl;
std::cin.ignore();
client.CloseSocket();
server.CloseSocket();
CryptoPP::Socket::ShutdownSockets();
Client:
CryptoPP::Socket client;
CryptoPP::socklen_t size_sock = sizeof(sockaddr_in);
timeval timev = {3, 0};
std::string test;
Socket::StartSockets();
client.Create(SOCK_STREAM);
client.Connect("127.0.0.1", 4213);
std::cout << "connected" << std::endl;
while (!client.ReceiveReady(&timev));
CryptoPP::SocketSource(client, true, new StringSink(test));
std::cout << test << std::endl;
std::cin.ignore();
client.CloseSocket();
Socket::ShutdownSockets();
What happens now: The connection is established as wished, and the server sends the data, the client receives it and waits at cin.ignore(). But the server seemes to hang up while sending, because it won't print "Data send". It only does this, when the client closes the connection.
My question now is, am I doing something wrong, or is this just the normal behavior of SocketSource and SocketSink and i have to reconnect everytime...
Thanks for your help :)
The following is from test.cpp. It might give you some ideas. I don't recall reading on how to use them (and I've never used them in a program). Its the only place I've ever seen PumpAll2 and non-blocking used.
You might find they work better on Windows than Linux.
void ForwardTcpPort(const char *sourcePortName, const char *destinationHost,
const char *destinationPortName)
{
SocketsInitializer sockInit;
Socket sockListen, sockSource, sockDestination;
int sourcePort = Socket::PortNameToNumber(sourcePortName);
int destinationPort = Socket::PortNameToNumber(destinationPortName);
sockListen.Create();
sockListen.Bind(sourcePort);
setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, "\x01", 1);
cout << "Listing on port " << sourcePort << ".\n";
sockListen.Listen();
sockListen.Accept(sockSource);
cout << "Connection accepted on port " << sourcePort << ".\n";
sockListen.CloseSocket();
cout << "Making connection to " << destinationHost << ", port " << destinationPort << ".\n";
sockDestination.Create();
sockDestination.Connect(destinationHost, destinationPort);
cout << "Connection made to " << destinationHost << ", starting to forward.\n";
SocketSource out(sockSource, false, new SocketSink(sockDestination));
SocketSource in(sockDestination, false, new SocketSink(sockSource));
WaitObjectContainer waitObjects;
while (!(in.SourceExhausted() && out.SourceExhausted()))
{
waitObjects.Clear();
out.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - out", NULL));
in.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - in", NULL));
waitObjects.Wait(INFINITE_TIME);
if (!out.SourceExhausted())
{
cout << "o" << flush;
out.PumpAll2(false);
if (out.SourceExhausted())
cout << "EOF received on source socket.\n";
}
if (!in.SourceExhausted())
{
cout << "i" << flush;
in.PumpAll2(false);
if (in.SourceExhausted())
cout << "EOF received on destination socket.\n";
}
}
}