I'm kinda new to network programming and I'm trying to make a socket server that could handle multiple clients. The server will be a connection between players and a game engine for a text-based adventure, written in c++.
I got the code working for single clients, and for sending data between client and server. The next step in the implementation is to make it able to handle multiple clients. For what I understand fork is way to do this. I've got this code this far, but I can't for my life get it to work.
while (1) {
cout << "Server waiting." << endl;
n = sizeof(struct sockaddr_in);
if ((clientSocket = accept(servSocket, (struct sockaddr*) (&client), (socklen_t*) (&n))) < 0) {
cerr << "Error: " << errno << ": " << strerror(errno) << endl;
}
if(fork() == 0){
cout << "Child process created. Handling connection with << " << inet_ntop(AF_INET, &client.sin_addr, buff, sizeof(buff)) << endl;
close(servSocket);
}
string sendmsg;
string recvmsg;
int bytesRecieved = 0;
char package[1024];
string playerMessage;
while(1){
bytesRecieved = recv(clientSocket, package, 1024, 0);
for (int offset = 0; offset < bytesRecieved/sizeof(char); ++offset) {
playerMessage += package[offset];
}
cout << playerMessage;
cin >> sendmsg;
sendmsg += "\n";
send(clientSocket, sendmsg.c_str(), sendmsg.size(), 0);
}
}
close(clientSocket);
close(servSocket);
return 0;
I understand that the bind() and everything before that should happend before the main-loop with fork() in it, so I didn't bother to include that.
Thanks on beforehand!
Creating process per connection is a wrong way in most cases. What if you have 20'000 players? Context switching for 20'000 processes makes too much overhead slowing down the server.
Consider using async programming. boost::asio is one of the best choices then.
Related
I am writing a C++ server program and a Qt client program. The problem is, recv() keeps waiting forever when tcpdump clearly shows a tcp packet from client is delivered to my network interface.
Server program is ran on Centos 7.7 and compiled with g++ 4.8.5
while (true) {
sockaddr_in client_addr{0};
socklen_t client_len = sizeof(sockaddr_in);
newsockfd = accept(sockfd, (sockaddr*)&client_addr, &client_len);
cout << "New connection from " << inet_ntoa(client_addr.sin_addr) << endl;
long bytes;
char buf[1000];
while (true) {
bytes = recv(newsockfd, buf, 1000, 0);
if (bytes < 1) {
if (bytes < 0) { cout << "Error: " << errno << ", " << strerror(errno) << endl; }
break;
}
ProcessRequest(buf, bytes);
}
close(newsockfd);
cout << "Host " << inet_ntoa(client_addr.sin_addr) << " disconnected..." << endl;
}
Client program is ran on Windows and compiled with msvc 2017 and Qt:
QTcpSocket* loginClient = new QTcpSocket(this);
loginClient->connectToHost(ipAddr, Port);
if (!loginClient->waitForConnected(30000)) { return; }
char data[100] = "12345678";
int sendLen = loginClient->write(data, 9);
if (sendLen == -1) { return; }
The server is able to detect connection from client, so ip and port issues are out of the way. Furthermore, the server is not able to detect disconnection from this Qt client properly. Disconnection detection is usually postponed by numerous minutes or indefinitely.
An interesting thing is, I wrote another client program ran on another Centos, with which the server worked Perfectly. So I assume the server program is fine?
Thanks for any help.
Found the error. Turned out that Client side had made three connections to the server among which only one was connected and two in queue. The packet was coming into the server not from the connected socket. That is why the opened file descriptor doesn't read anything from NIC.
I'm writing a client/server application where the client and server should send data to each other via a TCP socket. The client should connect to the server and if the connection fails, it should wait a few seconds and then try again to connect to it (up to a certain number of tries).
This is the code I currently have:
const int i_TRIES = 5;
time_t t_timeout = 3000;
int i_port = 5678;
int i_socket;
string s_IP = "127.0.0.1";
for(int i = 0; i < i_TRIES; i++)
{
if((i_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
cout << "[Client]: Socket creation failed." << endl;
exit(EXIT_FAILURE);
}
memset(&server_address, '0', sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(i_port);
if(inet_pton(AF_INET, s_IP.c_str(), &server_address.sin_addr) <= 0)
{
cout << "[Client]: Invalid IP address." << endl;
exit(EXIT_FAILURE);
}
if(connect(i_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
if(i < i_TRIES - 2)
{
cout << "[Client]: Connection to server failed. Trying again in " << t_timeout << " ms." << endl;
close(i_socket);
sleep(t_timeout);
}
else
{
cout << "[Client]: Could not connect to server, exiting." << endl;
exit(EXIT_FAILURE);
}
}
else
{
cout << "[Client]: Successfully connected to server." << endl;
break;
}
}
// do stuff with socket
The issue I'm having is that the first call to connect() works as expected, it fails if there's no server and then the loop repeats, however, the second time connect() blocks forever (or at least for much longer than I want it to). Initially, my loop was just around the connect() if block (code below), and this also caused the same problem. After that I included the whole socket setup (the code above) in the loop, but that also didn't help. I also tried closing the socket after a failed connection, but this didn't help either.
Initial for loop:
// other stuff from above here
for(int i = 0; i < i_TRIES; i++)
{
if(connect(i_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
{
if(i < i_TRIES - 2)
{
cout << "[Client]: Connection to server failed. Trying again in " << t_timeout << " ms." << endl;
sleep(t_timeout);
}
else
{
cout << "[Client]: Could not connect to server, exiting." << endl;
exit(EXIT_FAILURE);
}
}
else
{
cout << "[Client]: Successfully connected to server." << endl;
break;
}
}
// do stuff with socket
Can I force connect() to return after a certain amount of time has passed? Or is there a way to get the connect() function to try multiple times on it's own? Or is there something I need to do to the socket to reset everything before I can try again? I hope this isn't a dumb question, I couldn't find any information about how to connect multiple times.
Thanks in advance!
Can I force connect() to return after a certain amount of time has passed?
No. You must put the socket into non-blocking mode and then use select() or (e)poll() to provide timeout logic while you wait for the socket to connect. If the connection fails, or takes too long to connect, close the socket, create a new one, and try again.
Or is there a way to get the connect() function to try multiple times on it's own?
No. It can perform only 1 connection attempt per call.
Or is there something I need to do to the socket to reset everything before I can try again?
There is no guarantee that you can even call connect() multiple times on the same socket. On some platforms, you must destroy the socket and create a new socket before you call connect() again. You should get in the habit of doing that for all platforms.
Put the socket into non-blocking mode and use select() to implement the timeout. Select for writeability on the socket. Note that you can decrease the platform connect timeout by this means, but not increase it.
The sleep() is pointless, just literally a waste of time.
I'm following the tutorial (big code block near the bottom of that section)
here:http://beej.us/guide/bgnet/output/html/multipage/advanced.html#select
And the main server code code is like so:
while (true)
{
read_fds = master;
if (select(fd_max + 1, &read_fds, NULL, NULL, NULL) == -1)
{
cerr << "ERROR. Select failed" << endl;
return -1;
}
for (int i = 0; i <= fd_max; i++)
{
if (FD_ISSET(i, &read_fds))
{
if (i == welcome_socket)
{
cout << "NEW CONNECTION" << endl;
client_len = sizeof(struct sockaddr_in);
client_sock = accept(welcome_socket, (struct sockaddr *) &client_addr, &client_len);
if (client_sock != -1)
{
FD_SET(client_sock, &master);
if (client_sock > fd_max)
{
fd_max = client_sock;
}
}
}
else
{
int length, total_read = 0;
// CONNECTION CLOSED BY CLIENT
if (safe_recv(client_sock, &length, sizeof(int)) <= 0)
{
cout << "CONNECTION CLOSED" << endl;
close(i);
FD_CLR(i, &master);
}
else
{
char *message = (char *)memset((char *)malloc(length + 1), 0, length);
// while ((total_read += safe_recv(client_sock, message + total_read, length - total_read)) < length) {}
safe_recv(client_sock, message, length);
// RESPOND WITH MESSAGE
cout << "MESSAGE: " << message << endl;
write(client_sock, process(message), length);
free(message);
}
}
}
}
}
What I'm doing is first sending (from the client) the length of the string, then the string itself. Then the server sends back process(message).
When I only have 1 connection, I'm seeing correct behaviour. However if 1 is connected already and I connect a new client, what I'm seeing is:
1st client no longer sends or receives anything from server (concluded because nothing is printed to stdout on client side)
2nd client is working as expected
When 2nd connection exits, server counts that as both connections exiting (prints CONNECTION CLOSED twice)
I've tried to keep this very similar to the tutorial code. I've run the tutorial server, and that works as intended with several clients.
I'm new to network programming, so I apologise if this is a beginner problem or just something dumb I overlooked.
The code reads from and writes to only client_sock, and client_sock is replaced with the new socket in the accept handling portion of the code.
Most likely you want to interact with i rather than client_sock.
hey guys i have been trying to make a simple console application to see my network traffic :P im trying to just read it.
anyways im getting an error from the WSAIoctl function and the error code WSAGetLastError is giving me is 10022 and the MSDN tells me that it is associated with this:
Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.
i have tried messing with the arguments without luck :/ please help me :P
here's my code:
WSADATA wsaData;
int startup = WSAStartup(0x0202, &wsaData);
if(startup != 0) {
cout << "Error: could not initalize WSADATA for target socket." << endl;
system("pause");
}
unsigned long BytesReturned;
int InBuffer, OutBuffer, LPCVoid;
int optValue = 1;
SOCKET sock = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
Sleep(await);
cout << "creating and configuring RAW_SOCK" << endl;
int listening = listen(sock, SOMAXCONN); // tried debugging using this.
int sockopt = setsockopt(sock, IPPROTO_IP, 2, (char*)&optValue, sizeof(optValue));
int SockMode = WSAIoctl(sock, SIO_RCVALL, &InBuffer, sizeof(InBuffer), &OutBuffer, sizeof(OutBuffer), &BytesReturned, NULL, NULL);
//0x98000001
if(SockMode == 0) {
Sleep(await);
cout << "RAW_SOCKET created successfully!" << endl << "Trying to listen for incoming network packets..." << endl;
int listeningk = listen(sock, SOMAXCONN);
if(listening == 0) {
Sleep(await);
cout << "socket listening without problems, looking for incoming request..." << endl;
}
else {
Sleep(await);
cout << "Error: could not listen on socket." << endl;
exit(EXIT_FAILURE);
}
}
else {
Sleep(await);
cout << "Error: could not create RAW_SOCKET..." << endl << "Dumping SockMode!\r\nint SockMode = " << SockMode << endl;
cout << "setsockopt = " << sockopt << endl;
cout << "WSAGetLastError: " << WSAGetLastError() << endl;
system("pause");
}
Your socket needs to be bound before you can listen. Moreover for this WSAIoctl option you have to obey (from the MSDN docs):
The socket also must be bound to an explicit local IPv4 or IPv6
interface, which means that you cannot bind to INADDR_ANY or
in6addr_any.
I'd suggest some basic self-education is in order before trying to progress this code. There are code samples for common ops like socket setup in MSDN.
I am trying to write a threaded function that sends system information via Tcp/ip over the local network to another computer. I have been using sockets to achieve this and this has worked out quite allright thus far. But I am now at a point where this usually works but around 30% of the time I get error messages telling me that the socket can not be opened. I use the activeSocket library for the sockets.
#include "tbb/tick_count.h"
#include "ActiveSocket.h"
using namespace std;
CActiveSocket socket;
extern int hardwareStatus;
int establishTCP() {
char time[11];
int communicationFailed = 0;
memset(&time, 0, 11);
socket.Initialize();
socket.SetConnectTimeout(0, 20);
socket.SetSendTimeout(0, 20);
return communicationFailed;
}
int monitor() {
cout << "Monitor: init continious monitoring" << endl;
int communicationFailed;
tbb::tick_count monitorCounter = tbb::tick_count::now();
while (!closeProgram) {
tbb::tick_count currentTick = tbb::tick_count::now();
tbb::tick_count::interval_t interval;
interval = currentTick - monitorCounter;
if (interval.seconds() > 2) {
monitorCounter = tbb::tick_count::now();
communicationFailed = 1;
char buffer[256];
sprintf(buffer, "%d;", hardwareStatus);
establishTCP();
char *charip = new char[monitoringIP.size() + 1];
charip[monitoringIP.size()] = 0;
memcpy(charip, monitoringIP.c_str(), monitoringIP.size());
const uint8* realip = (const uint8 *) charip;
int monitorCount = 0;
cout << "Monitor: " << buffer << endl;
while (communicationFailed == 1 && monitorCount < 2) {
monitorCount++;
if (socket.Open(realip, 2417)) {
if (socket.Send((const uint8 *) buffer, strlen(buffer))) {
cout << "Monitor: Succeeded sending data" << endl;
communicationFailed = 0;
socket.Close();
} else {
socket.Close();
communicationFailed = 1;
cout << "Monitor: FAILED TO SEND DATA" << endl;
}
} else {
socket.Close();
communicationFailed = 1;
cout << "Monitor: FAILED TO OPEN SOCKET FOR DATA" << endl;
}
}
if (monitorCount == 2) cout << "Monitor: UNABLE TO SEND DATA" << endl;
}
}
return communicationFailed;
}
I think I am doing something wrong with these functions and that the problem is not on the other side of the line where this data is received. Can anyone see any obvious mistakes in this code that could cause the failure? I keep getting my own cout message "Monitor: FAILED TO OPEN SOCKET FOR DATA"
EDIT: With telnet everything works fine, 100% of the time
You can use netstat to check that the server is listening on the port and connections are being established. Snoop is another good application in your Armour for finding out what is going wrong. Another possibility is to use telnet to see if the client can connect to that IP address and port. As to the code I will take a look at it later to see if something has gone awry.
socket is a global variable. It might be re-used concurrently between two threads or sequentially inside one thread. In fact, the while(~closeProgram) loop indicates that you intend to use it sequentially.
Some documentation for CActiveSocket::Open reads: "Connection-based protocol sockets (CSocket::SocketTypeTcp) may successfully call Open() only once..."
Perhaps your program fails when you call .Open() twice on the same object.
I eventually found out the problem with my code. As the connection was unstable and working for 70% of the time it seemed to be a timeout issue. I removed the two timeout settings
socket.SetConnectTimeout(0, 20);
socket.SetSendTimeout(0, 20);
Now it works perfectly fine, thanks for the troubleshooting tips though!