I have a client and server set up to talk to each other. But every time I try to echo back to the client the socket seems to have disconnected. Much of the code is adapted from a sockets tutorial over at yolinux. Also, I'm running this remotely over ssh.
Client:
#include <cerrno>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <string>
#include <sstream>
using namespace std;
main(int argc, char *argv[])
{
if (argc != 3) {
cout << "exiting\n";
exit(EXIT_FAILURE);
}
struct sockaddr_in remoteSocketInfo;
struct hostent *hPtr;
int socketHandle;
char *remoteHost = argv[1];
int portNumber = atoi(argv[2]);
cout << "Welcome!\n";
// create socket
if ((socketHandle = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0)
{
cout << "Socket creation failed.\n";
close(socketHandle);
exit(EXIT_FAILURE);
}
cout << "Socket created!\n";
bzero(&remoteSocketInfo, sizeof(sockaddr_in)); // Clear structure memory
if ((hPtr = gethostbyname(remoteHost)) == NULL)
{
cerr << "System DN name resolution not configured properly.\n";
cerr << "Error number: " << ECONNREFUSED << endl;
exit(EXIT_FAILURE);
}
// Load system information for remote socket server into socket data structures
memcpy((char*)&remoteSocketInfo.sin_addr, hPtr->h_addr, hPtr->h_length);
remoteSocketInfo.sin_family = AF_INET;
remoteSocketInfo.sin_port = htons((u_short)portNumber); // set port number
if (connect(socketHandle, (struct sockaddr *)&remoteSocketInfo, sizeof(sockaddr_in)) < 0) {
cout << "connection failed\n";
close(socketHandle);
exit(EXIT_FAILURE);
}
cout << "Connected!\n";
string input;
int message;
while (1) {
cout << "Please indicate rotation amount:";
cin >> input;
if (input == "exit") {
close(socketHandle);
break;
}
char buf[input.length()+1];
const char *conv_input = input.c_str();
strcpy(buf, conv_input);
int bytes_sent = 0;
if ( (bytes_sent = send(socketHandle, buf, strlen(buf)+1, 0)) < 0) {
char buffer[256];
char * errorMessage = strerror_r( errno, buffer, 256);
cout << errorMessage << endl;
close(socketHandle);
exit(EXIT_FAILURE);
}
cout << "bytes sent: " << bytes_sent << endl;
int rc;
char buf2[input.length()+1];
rc = recv(socketHandle, buf2, strlen(buf)+1, 0);
buf[rc] = (char)NULL; // Null terminate string
cout << "received: " << buf2 << endl;
cout << "bytes received: " << rc << endl;
}
close(socketHandle);
}
Server:
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>
#define MAXHOSTNAME 256
using namespace std;
main(int argc, char *argv[])
{
if (argc != 2) {
cout << "not enough arguments, ex: ./CaesarCipherServer 9876\n";
exit(EXIT_FAILURE);
}
struct sockaddr_in socketInfo;
char sysHost[MAXHOSTNAME+1]; // Hostname of this computer we're running on
struct hostent *hPtr;
int portNumber = atoi(argv[1]);
int sock;
bzero(&socketInfo, sizeof(sockaddr_in)); // Clear structure memory
// Get system information
gethostname(sysHost, MAXHOSTNAME); // Get this computer's hostname
if ((hPtr = gethostbyname(sysHost)) == NULL)
{
cerr << "System hostname misconfigured." << endl;
exit(EXIT_FAILURE);
}
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
close(sock);
exit(EXIT_FAILURE);
}
// Load system info into socket data structures
socketInfo.sin_family = AF_INET;
socketInfo.sin_addr.s_addr = htonl(INADDR_ANY); // Use any addr available
socketInfo.sin_port = htons(portNumber); // Set port number
// Bind the socket to a local socket address
if (bind(sock, (struct sockaddr *) &socketInfo, sizeof(socketInfo)) < 0)
{
close(sock);
perror("bind");
exit(EXIT_FAILURE);
}
cout << "listening for initial connection \n";
listen(sock, 1);
int sockConn;
if ((sockConn = accept(sock, NULL, NULL)) < 0)
{
exit(EXIT_FAILURE);
} else {
cout << "connection accepted!\n";
}
int rc = 0;
char buf[512];
cout << "about to receive message... \n";
// rc is number of chars returned
rc = recv(sockConn, buf, 512, 0);
buf[rc] = (char)NULL; // Null terminate string
cout << "received: " << buf << endl;
cout << "rc: " << rc << endl;
int bytes_sent;
if ((bytes_sent = send(sock, buf, rc, MSG_NOSIGNAL)) < 0) {
cout << "error sending\n";
close(sock);
exit(EXIT_FAILURE);
}
cout << "bytes sent: " << bytes_sent << endl;
close(sock);
}
Client Output:
./CaesarCipherClient cs-ssh 9876
Welcome!
Socket created!
socket handle : 3
Connected!
Please indicate rotation amount:5
bytes sent: 2
received:
bytes received: 0
Please indicate rotation amount:
Server Output:
./CaesarCipherServer 9876
listening for initial connection
connection accepted!
about to receive message...
received: 5
rc: 2
error sending
If the MSG_NOSIGNAL flag isn't specified, the server crashes at send(), which means the socket has disconnected at the other end. Why would the socket consistently disconnect after a send()/recv() pair?
I apologize for any poor readability/style/pure stupidity in my submission.
Thank you for your help!
In your server, you are using:
if ((bytes_sent = send(sock, buf, rc, MSG_NOSIGNAL)) < 0) {
cout << "error sending\n";
close(sock);
exit(EXIT_FAILURE);
}
Here, sock is the listening socket, not the accepted client socket. You need to replace sock with sockCon instead (which you are using in your recv() function call, and that is working).
Related
I'm using ubuntu 20.04 now. I have text file in client document. The server can listen the port and I can sen the file but when I open it, there is no text.
client code;
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
const int BUFSIZE = 4096;
int main(int argc, char *argv[]) {
int client_socket;
struct sockaddr_in server_address;
char buffer[BUFSIZE];
// Create a socket
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket < 0) {
std::cerr << "Failed to create socket" << std::endl;
return 1;
}
// Set up the server address
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(12345);
if (inet_aton("127.0.0.1", &server_address.sin_addr) == 0) {
std::cerr << "Invalid address" << std::endl;
return 1;
}
// Connect to the server
if (connect(client_socket, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
std::cerr << "Failed to connect to server" << std::endl;
return 1;
}
std::cout << "Connected to server at " << inet_ntoa(server_address.sin_addr) << ":" << ntohs(server_address.sin_port) << std::endl;
// Send the file
std::ifstream input_file("file_to_send.txt", std::ios::binary); //
int bytes_sent;
while (input_file.read(buffer, BUFSIZE)) {
bytes_sent = send(client_socket, buffer, input_file.gcount(), 0);
if (bytes_sent < 0) {
std::cerr << "Failed to send data" << std::endl;
break;
}
}
input_file.close();
close(client_socket);
std::cout << "File 'file_to_send.txt' sent" << std::endl;
return 0;
}
server code;
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
const int BUFSIZE = 4096;
int main(int argc, char *argv[]) {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
socklen_t client_address_len;
char buffer[BUFSIZE];
// Create a socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
std::cerr << "Failed to create socket" << std::endl;
return 1;
}
// Set up the server address
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(12345);
// Bind the socket to the server address
if (bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) {
std::cerr << "Failed to bind socket" << std::endl;
return 1;
}
// Listen for incoming connections
if (listen(server_socket, 5) < 0) {
std::cerr << "Failed to listen on socket" << std::endl;
return 1;
}
std::cout << "Listening for incoming connections on port 12345.." << std::endl;
// Accept an incoming connection
client_address_len = sizeof(client_address);
client_socket = accept(server_socket, (struct sockaddr *) &client_address, &client_address_len);
if (client_socket < 0) {
std::cerr << "Failed to accept connection" << std::endl;
return 1;
}
std::cout << "Accepted connection from " << inet_ntoa(client_address.sin_addr) << std::endl;
// Receive the file
std::ofstream output_file("received_file.txt", std::ios::binary);
int bytes_received;
std::cout << "Bytes received: " << bytes_received << std::endl;
while( (bytes_received = recv(client_socket, buffer, BUFSIZE,0)))>0{
std::cout << "Bytses recieved are not null." << std::endl;
output_file.write(buffer , bytes_received); }
output_file.close();
close(client_socket);
close(server_socket);
std::cout << "File received and saved as 'received_file.txt'" << std::endl;
return 0;
}
I added sys/socket.h library but I think there is a problem in line 65. I ran the server and client. On terminaL, I see "Connected to server at" and "File 'file_to_send.txt' sent". And for server, I see "Listening for incoming connections on port","Accepted connection from ", "Bytes received: 0" and "File received and saved as 'received_file.txt'". "Hello world" is written in the text file I'm new to this topic so I don't know what to do properly. How can I handle this? Thank you.
I'm supposed to use get_nprocs_conf() to get the number of execution contexts on my machine. I'm doing this because I am coding a server and client to interact with each other, and the server may only host get_nprocs_conf()-1 clients. Before I add code to my server to wait for an opening, I want to figure out this issue.
I'm running this code on a virtual machine because I'm using Linux and my desktop is Windows, and when I use said code above, my maximum number of clients is 0, meaning that get_nprocs_conf() only returns 1. Is this because I'm using a virtual machine and for some reason it only can use one execution context, or am I misunderstanding and my computer only has one execution context?
Provided below are my server and client programs.
Server Code:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <sys/sysinfo.h>
#include <vector>
#include <cstring>
#include <arpa/inet.h>
//#define BUFFER_SIZE 32
//May need to replace -1 with EXIT_FAILURE in all the exits
int main(int argc, char *argv[]) {
if(argc != 2) {
std::cout << "Need domain socket file name" << std::endl;
exit(-1);
}
struct sockaddr_un server;
char buffer[32];
unlink(argv[1]);
int serverSock = socket(AF_UNIX, SOCK_STREAM, 0);
if(serverSock < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
std::clog << "SERVER STARTED" << std::endl;
size_t maxClients = get_nprocs_conf()-1;
std::clog << "\t" << "MAX CLIENTS: " << maxClients << std::endl;
memset(&server, 0, sizeof(server));
server.sun_family = AF_UNIX;
strncpy(server.sun_path, argv[1], sizeof(server.sun_path)-1);
int success = bind(serverSock, (const struct sockaddr *) &server,
sizeof(struct sockaddr_un));
if(success < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
success = listen(serverSock, maxClients);
if(success < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
while(true) {
std::cout << "Waiting for clients" << std::endl;
int clientSock = accept(serverSock, nullptr, nullptr);
if(clientSock < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
std::clog << "CLIENT CONNECTED" << std::endl;
std::string path="";
std::string searchStr="";
char fileBuff[32];
char searchBuff[32];
memset(fileBuff, 0, 32);
success = read(clientSock, fileBuff, 32);
if(success < 0) {
perror("read");
exit(EXIT_FAILURE);
}
path = fileBuff;
std::cout << path << std::endl;
if(path.empty()) {
std::cout << "No path to file given" << std::endl;
exit(1);
}
memset(searchBuff, 0, 32);
success = read(clientSock, searchBuff, 32);
if(success < 0) {
perror("read");
exit(EXIT_FAILURE);
}
searchStr = searchBuff;
std::cout << searchStr << std::endl;
if(searchStr.empty()) {
std::cout << "No search string given" << std::endl;
exit(1);
}
std::ifstream inFile;
inFile.open(path);
std::string line = "";
int bytesSent = 0;
std::vector<std::string> allLines;
if(inFile.is_open()) {
while(std::getline(inFile, line)) {
if(line.find(searchStr, 0)!=std::string::npos) {
allLines.push_back(line);
//std::cout << line << std::endl;
}
}
}
//Sending over entire length of vector containing all lines to be sent.
long length = htonl(allLines.size());
success = write(clientSock, &length, sizeof(length));
if(success < 0) {
perror("write");
exit(EXIT_FAILURE);
}
for(int b=0; b<allLines.size(); b++) {
length = htonl(allLines[b].length());
success = write(clientSock, &length, sizeof(length));
if(success < 0) {
perror("write");
exit(EXIT_FAILURE);
}
success = write(clientSock, allLines[b].data(), allLines[b].length());
if(success < 0) {
perror("write");
exit(EXIT_FAILURE);
}
bytesSent += allLines[b].length();
}
//char end[] = {'\n'};
//write(clientSock, end, sizeof(char));
std::cout << "BYTES SENT: " << bytesSent << std::endl;
inFile.close();
close(clientSock);
}
//return 0;
}
Client Code:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <fstream> //Don't think I'll need this
#include <errno.h>
#include <sys/un.h>
#include <sstream>
#include <arpa/inet.h>
#include <vector>
int main(int argc, char *argv[]){
if(argc != 4) {
std::cout << "Need domain socket file name, file path and name, " <<
"and search string" << std::endl;
exit(-1);
}
struct sockaddr_un client;
char buffer[64]; //Prof had 64 for client may need to change to 32 to match
int clientSock = socket(AF_UNIX, SOCK_STREAM, 0);
if(clientSock < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
std::cout << "socket connected" << std::endl;
memset(&client, 0, sizeof(struct sockaddr_un));
client.sun_family = AF_UNIX;
strncpy(client.sun_path, argv[1], sizeof(client.sun_path)-1);
int connectClient = connect(clientSock, (const struct sockaddr *)&client,
sizeof(struct sockaddr_un));
if(connectClient < 0) {
fprintf(stderr, "The server is not working.\n");
exit(EXIT_FAILURE);
}
std::cout << "client connected" << std::endl;
//char arg2[] = {*argv[2],'\n'};
std::string path = argv[2];
std::cout << "Path: " << path << std::endl;
connectClient = write(clientSock, argv[2], path.length());
if(connectClient < 0) {
perror("write");
exit(EXIT_FAILURE);
}
std::string search = argv[3];
std::cout << "Search String: " << search << std::endl;
connectClient = write(clientSock, argv[3], search.length());
if(connectClient < 0) {
perror("write");
exit(EXIT_FAILURE);
}
//int servRet;
int lineCount=0;
int bytes_received=0;
//std::string line = "";
char length[sizeof(int)];
//std::string leng = "";
int num=0;
std::stringstream ss;
std::vector<std::string> allLines;
long size = 0;
read(clientSock, &size, sizeof(size));
size = ntohl(size);
for(int a=0; a<size; ++a) {
long length = 0;
std::string line = "";
connectClient = read(clientSock, &length, sizeof(length));
length = ntohl(length);
while(0 < length) {
char buffer[1024];
connectClient = read(clientSock, buffer, std::min<unsigned long>(sizeof(buffer),length));
line.append(buffer, connectClient);
length-=connectClient;
}
allLines.push_back(line);
lineCount++;
std::cout << lineCount << "\t" << line << std::endl;
bytes_received += line.length();
}
std::cout << "BYTES RECEIVED: " << bytes_received << std::endl;
close(clientSock);
return 0;
}
Right now everything in the server and client work as they should. I'm just hesitating to add code that waits for an execution context to open for another client to be read because it seems like it would never accept any clients since the sole execution context is being used by the server. Any clarification on my issue or on if I'm just using get_nprocs_conf() incorrectly would be greatly appreciated.
The way my code is currently written only allows a message from the server to be read directly after input is taken and a message is sent. However, this code is for a chat server and must allow a read to occur at any time a message is sent.
#include <iostream>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_ADDRESS "127.0.0.1"
constexpr int server_port = 15555;
#define SERVER_SUCCESS "1"
#define SERVER_FAILURE "-1"
constexpr int msg_buffer_size = 4096;
int main(int argc, char *argv[])
{
struct sockaddr_in serv_addr;
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
std::cerr << "Socket creation failed!" << std::endl;
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(server_port);
if (inet_pton(AF_INET, SERVER_ADDRESS, &serv_addr.sin_addr) <= 0)
{
std::cerr << "Invalid server address!" << std::endl;
return 1;
}
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
std::cerr << "Failed to connect to chat server!" << std::endl;
return 1;
}
int valread;
while (true)
{
std::cout << ">> ";
char msg[msg_buffer_size];
char return_msg[msg_buffer_size];
std::string input;
std::getline(std::cin, input);
if (input == "quit")
return 0;
if (input.length() > 4000)
{
std::cout << "Input length must be less than 4000 characters." << std::endl;
continue;
}
strcpy(msg, input.c_str());
if (send(sock, msg, strlen(msg), 0) < 0)
{
std::cout << "Error sending data." << std::endl;
continue;
}
if (recv(sock, return_msg, msg_buffer_size, 0) < 0)
{
std::cout << "Error receiving data." << std::endl;
continue;
}
std::string code(strtok(return_msg, " "));
if (code == SERVER_FAILURE)
std::cout << "Failure: " << strtok(NULL, "") << std::endl;
else
std::cout << strtok(NULL, "") << std::endl;
memset(msg, 0, msg_buffer_size);
memset(return_msg, 0, msg_buffer_size);
}
std::cout << "Exiting." << std::endl;
close(sock);
return 0;
}
What would be a correct way to allow the client to receive a message as soon as one is sent from the server? I was thinking about making a thread, but it seemed kind of redundant since I would be receiving in two places.
I'm trying to build a little Chat App just between the Server and the Client. I stumbled across this YouTube video (GitHub source).
If I run both scripts everything works fine but if I try to put the Client-Side into an macOS Application the Client says that it has connected even though the Server isn't running.
Client.cpp
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include "Client.hpp"
using namespace std;
void connectToServer()
{
int client;
int portNum = 1600; // NOTE that the port number is same for both client and server
bool isExit = false;
int bufsize = 1024;
char buffer[bufsize];
char* ip = "127.0.0.1";
struct sockaddr_in server_addr;
client = socket(AF_INET, SOCK_STREAM, 0);
if (client < 0)
{
cout << "\nError establishing socket..." << endl;
exit(1);
}
cout << "\n=> Socket client has been created..." << endl;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portNum);
if (connect(client,(struct sockaddr *)&server_addr, sizeof(server_addr)) == 0)
cout << "=> Connection to the server port number: " << portNum << endl;
cout << "=> Awaiting confirmation from the server..." << endl; //line 40
recv(client, buffer, bufsize, 0);
std::cout << client << std::endl;
std::cout << buffer << std::endl;
cout << "=> Connection confirmed, you are good to go...";
cout << "\n\n=> Enter # to end the connection\n" << endl;
// Once it reaches here, the client can send a message first.
do {
cout << "Client: ";
do {
cin >> buffer;
send(client, buffer, bufsize, 0);
if (*buffer == '#') {
send(client, buffer, bufsize, 0);
*buffer = '*';
isExit = true;
}
} while (*buffer != 42);
cout << "Server: ";
do {
recv(client, buffer, bufsize, 0);
cout << buffer << " ";
if (*buffer == '#') {
*buffer = '*';
isExit = true;
}
} while (*buffer != 42);
cout << endl;
} while (!isExit);
cout << "\n=> Connection terminated.\nGoodbye...\n";
close(client);
}
ViewController.mm
- (void)viewDidLoad {
[super viewDidLoad];
connectToServer();
}
Console Output:
=> Socket client has been created...
=> Awaiting confirmation from the server...
=> Connection confirmed, you are good to go...
=> Enter # to end the connection
Client: test *
Server: *
Client:
This question already has an answer here:
Bind return error 88
(1 answer)
Closed 5 years ago.
I was searching for an answer for my issue though nothing relevant came up.
I'm writing a very simple code for running a server on a virtual machine (VBOX) running ubuntu 14.04.
I turned off my firewall and my anti-virus program (read that it might be related)
I rechecked (and looked for different ports) that the port is not in use but keep on receiving return value of -1 to the bind() function with errno 88 (socket operation on non-socket).
I'm running the server on port 7777.
Also tried running this code on my host
Can someone suggest what I am doing wrong?
p.s also checked the code with valgrind for memory leaks but it looks fine.
the code is as follows:
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <fstream>
#include <strings.h>
#include <stdlib.h>
#include <string>
#include <pthread.h>
#include <errno.h>
using namespace std;
#define NUM_OF_THREADS 3
static int connFd;
void *task1(void *);
/*
*
*/
int main(int argc, char** argv) {
int pid, portNo, listenFd;
socklen_t len; // store the size of the address
bool loop = false;
struct sockaddr_in svrAdd, clntAdd;
pthread_t threadArr[NUM_OF_THREADS];
if (argc < 2){
cerr << "ERROR: ./server <port>" << endl;
return 0;
}
portNo = atoi(argv[1]); // TODO verify the port is between 1024 and 65535
//Create the socket
if (listenFd = socket(AF_INET, SOCK_STREAM, 0) < 0){
cerr << "ERROR: cannot open socket." << endl;
return 0;
}
bzero((char*)&svrAdd, sizeof(svrAdd));
svrAdd.sin_family = AF_INET;
svrAdd.sin_addr.s_addr = INADDR_ANY;
svrAdd.sin_port = htons(portNo);
cout << "port number is : " << portNo << endl;
//bind socket
int bound = bind(listenFd, (struct sockaddr *)&svrAdd, sizeof(svrAdd));
if ( bound < 0 ){
cerr << "ERROR: cannot bind, error number: " << errno << endl;
return 0;
}
listen(listenFd, 5);
len = sizeof(clntAdd);
int noTread = 0;
while(noTread < 3){
cout << "Listening..." << endl;
if (connFd = accept(listenFd, (struct sockaddr*)&clntAdd, &len)<0){
cerr << "ERROR: cannot accept connection" << endl;
return 0;
}
else{
cout << "Connection successful" << endl;
}
pthread_create(&threadArr[noTread], NULL, task1, NULL);
noTread++;
}
for (int i=0; i < 3; i++){
pthread_join(threadArr[i], NULL);
}
/*int sockfd, newsockfd, portno, clilen, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2){
fprintf(stderr, "ERROR, no port provided");
exit(1);
}
if(sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0){
error("ERROR opening socket");
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr - INADDR_ANY;
if(bind(sockfd, (struct sockaddr*)&))*/
return 0;
}
void *task1(void *dummyPt){
cout << "Thread number: " << pthread_self() << endl;
char test[300];
bzero(test, 301);
bool loop = false;
while (!false){
bzero(test, 301);
read(connFd, test, 300);
string tester(test);
cout << "\n\t\t TESTER = " << tester << endl;
if(tester == "exit"){
break;
}
}
cout << "\n Closing thread and conn" << endl;
close(connFd);
}
The output of the execution:
ERROR: cannot bind, error number: 88
port number is : 7777
RUN SUCCESSFUL (total time: 162ms)
Please help,
Thanks.
if (listenFd = socket(AF_INET, SOCK_STREAM, 0) < 0){
Precedence problem. The result of this condition is to assign zero or 1 to listenFd. Try this:
if ((listenFd = socket(AF_INET, SOCK_STREAM, 0)) < 0){