[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[LCP]multi-threaded server



hi all,
i have written code for a server program which waits for clients to
connect. seperate thread for each client connection. on connection
recieves requets, work on requets and then send the result. but the
problem is that the threads arent closed on client disconnecting.


/***************** start code ******************************/


#define PORT 18000


#include "dougnet.h"
#include "session.h"
#include "common.h"
#include "common1.h"

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string>
#include <iostream>
#include <fstream>

ReadConf readConf;
ofstream fpLog;

void *session(void *connfd)
{
	std::string buf1;
	std::string cmd;
	int recvCnt;

pthread_detach(pthread_self());

recvCnt = recv_line((int)connfd, buf1);
if(!recvCnt) {
return NULL;
}/* if(!recvCnt) */
writeToLogFile<std::string, std::string, std::string>("buf1 = ", buf1, "\n");


/*IMP. !!! login part to be added. */
recvCnt = recv_line((int)connfd, cmd);
if(!recvCnt) {
return NULL;
}/* if(!recvCnt) */
writeToLogFile<std::string, std::string, std::string>("cmd = ", cmd, "\n");


struct request *rs;

	for (rs = requests; rs->name != NULL; ++rs) {
		if(strcmp (cmd.c_str(), rs->name) == 0) {
			(*rs->func) ((int)connfd, buf1);
		}/* if(strcmp (cmd.c_str(), rs->name) == 0) */
	}/* for */
	writeToLogFile<std::string>("done\n");

	closesock((int)connfd);
	writeToLogFile<std::string>("socket closed\n");

	/* pthread_exit(NULL); */
	return(NULL);
}/* session() */

int main(int argc, char *argv[])
{
	int  s, t, res;
	char tpbuf[16];
	pthread_t tid;
	void      *thread_result;

	s = openlistener(PORT);
	if(s == (int) NULL) {
		exit(0);
	}/* if(s == (int) NULL) */

res = readConf.ReadConfFile(CONF_FILE_PATH);
if(!res) {
printf("error while reading config file %s\n", CONF_FILE_PATH);
return -1;
}/* if(!res) */


	std::string logfile;
	logfile = readConf.LogDir() + "/" + readConf.LogFileName();
	printf("logfile = %s\n", logfile.c_str());

fpLog.open(logfile.c_str(), ios::app);

	while(1) {
		if(pollsocket(s, 10000)) {
			t = acceptfromlistener(s, tpbuf);

			int res = pthread_create(&tid, NULL, &session, (void *)t);
			if(res) {
				printf("failed to create thread. %s", strerror(errno));
			}/* if(res) */

printf("Connection from %s\n", tpbuf);

}/* if(pollsocket(s, 10000)) */

		/*
		res = pthread_join(tid, &thread_result);
		if(res != 0) {
			perror("error join");
			exit(1);
		}
		*/
	}/* while(1) */

	return 0;
}/* main() */


/***************** end code ******************************/ ___________________________________________________ Meet your old school or college friends from 1 Million + database... Click here to reunite www.batchmates.com/rediff.asp