Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #include <vector>
- using namespace std;
- std::vector<pthread_t> threads;
- std::vector<int> clients;
- int serverSd;
- void* connectToClient(void* serverSd);
- void waitForConnection() {
- while(true) {
- sockaddr_in newSockAddr;
- socklen_t newSockAddrSize = sizeof(newSockAddr);
- int newSd = accept(*(int*)serverSd, (sockaddr *)&newSockAddr, &newSockAddrSize);
- if(newSd < 0)
- {
- cerr << "Error accepting request from client!" << endl;
- close(newSd);
- continue;
- }
- pthread_t tempThead;
- threads.push_back(tempThead);
- clients.push_back(newSd);
- pthread_create(&tempThead,NULL,&connectToClient,(void*)newSd);
- }
- }
- void* connectToClient(void* newSd) {
- int currentPosition = clients.size() - 1;
- char msg[250];
- cout << "Connected with client!" << endl;
- while(1) {
- cout << "Awaiting client response..." << endl;
- memset(&msg, 0, sizeof(msg));//clear the buffer
- recv(*(int *) newSd, (char *) &msg, sizeof(msg), 0);
- if (!strcmp(msg, "exit")) {
- cout << "Client has quit the session" << endl;
- break;
- }
- for (int i = 0; i < clients.size(); i++) {
- send(clients[i], (char *) &msg, strlen(msg), 0);
- }
- }
- clients.erase(clients.begin() + currentPosition);
- close(*(int*)newSd);
- }
- int main(int argc, char *argv[])
- {
- if(argc != 2)
- {
- cerr << "Usage: port" << endl;
- exit(0);
- }
- int port = atoi(argv[1]);
- sockaddr_in servAddr;
- bzero((char*)&servAddr, sizeof(servAddr));
- servAddr.sin_family = AF_INET;
- servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- servAddr.sin_port = htons(port);
- serverSd = socket(AF_INET, SOCK_STREAM, 0);
- if(serverSd < 0)
- {
- cerr << "Error establishing the server socket" << endl;
- exit(0);
- }
- int bindStatus = bind(serverSd, (struct sockaddr*) &servAddr,
- sizeof(servAddr));
- if(bindStatus < 0)
- {
- cerr << "Error binding socket to local address" << endl;
- exit(0);
- }
- cout << "Waiting for a client to connect..." << endl;
- listen(serverSd, 5);
- waitForConnection();
- close(serverSd);
- cout << "Connection closed..." << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement