GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 29-Dec-2005, 07:06
jaro's Avatar
jaro jaro is offline
Junior Member
 
Join Date: Nov 2005
Location: somewhere in souteast asia
Posts: 59
jaro will become famous soon enough

How to listens to two different ports at the same time


hi there,
i've got this code that listens for incomming message through port and display the message it recieves..
here's the code:

CPP / C++ / C Code:
#include "stdio.h" 
#include "winsock.h" 
#define PORT 1200 
#define BACKLOG 4 
struct sockaddr_in server; 
struct sockaddr_in client;
int sockfd,sockfd2,n_bytes; 
char msg[5000]; 
void handle_error(void);

int main(){ 

WSADATA wsda; 
WSAStartup(0x0101,&wsda); 

	if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ 
	handle_error();
	printf("Socket error..."); 
	return 0; 
	} 

server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(PORT);
server.sin_family=AF_INET; 

	if(bind(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ 
	handle_error();
	printf("Cannot bind..."); 
	return 0; 
	} 

	if(listen(sockfd,BACKLOG)){
	handle_error();
	printf("Error Listening..."); 
	return 0; 
	} 

	while (1){ 

	int size=sizeof(struct sockaddr_in); 

		if((sockfd2=accept(sockfd,(struct sockaddr*)&client,&size))==-1){ 
		handle_error();
		printf("Accept Error..."); 
		return 0; 
		} 

		if((n_bytes=recv(sockfd2,msg ,5000,0))==-1){ 
		handle_error();
		printf("Error Recv..."); 
		return 0; 
		} 

	msg[n_bytes]='\0'; 
	printf("Client's Message:%s",msg); 

	} 

WSACleanup(); 
closesocket(sockfd);
closesocket(sockfd2); 
return 0; 

} 


void handle_error(void)
{
  switch ( WSAGetLastError() )
  {
    case WSANOTINITIALISED :
      printf("Unable to initialise socket.\n");
    break;
    case WSAEAFNOSUPPORT :
      printf("The specified address family is not supported.\n");
    break;
    case WSAEADDRNOTAVAIL :
      printf("Specified address is not available from the local machine.\n");
    break;
    case WSAECONNREFUSED :
      printf("The attempt to connect was forcefully rejected.\n"); 
      break; 
    case WSAEDESTADDRREQ : 
      printf("address destination address is required.\n");
    break;
    case WSAEFAULT :
      printf("The namelen argument is incorrect.\n");
    break;
    case WSAEINVAL :
      printf("The socket is not already bound to an address.\n");
    break;
    case WSAEISCONN :
      printf("The socket is already connected.\n");
    break;
    case WSAEADDRINUSE :
      printf("The specified address is already in use.\n");
    break;
    case WSAEMFILE : 
      printf("No more file descriptors are available.\n");
    break;
    case WSAENOBUFS :
      printf("No buffer space available. The socket cannot be created.\n");
    break;
    case WSAEPROTONOSUPPORT :
      printf("The specified protocol is not supported.\n");
      break; 
    case WSAEPROTOTYPE :
      printf("The specified protocol is the wrong type for this socket.\n");
    break;
    case WSAENETUNREACH : 
      printf("The network can't be reached from this host at this time.\n");
    break; 
    case WSAENOTSOCK :
       printf("The descriptor is not a socket.\n");
    break;
    case WSAETIMEDOUT :
      printf("Attempt timed out without establishing a connection.\n");
    break;
    case WSAESOCKTNOSUPPORT :
       printf("Socket type is not supported in this address family.\n");
    break;
    case WSAENETDOWN :
      printf("Network subsystem failure.\n");
    break;
    case WSAHOST_NOT_FOUND :
      printf("Authoritative Answer Host not found.\n");
    break;
    case WSATRY_AGAIN :
      printf("Non-Authoritative Host not found or SERVERFAIL.\n");
     break;
    case WSANO_RECOVERY :
       printf("Non recoverable errors, FORMERR, REFUSED, NOTIMP.\n");
    break;
    case WSANO_DATA :
      printf("Valid name, no data record of requested type.\n");
    break;
      case WSAEINPROGRESS :
      printf("address blocking Windows Sockets operation is in progress.\n");
    break;
    case WSAEINTR :
      printf("The (blocking) call was canceled via WSACancelBlockingCall().\n");
    break;
    default :
      printf("Unknown error.\n");
     break;
  }

}

i've run/tested this and it works fine...
...now i want for the program to listens to two different ports and display the message it recieves through them (ports)...

so i've try to edit the code above to this ( not quite sure if it the right thing to do though ):

CPP / C++ / C Code:
#include "stdio.h" 
#include "winsock.h" 
#define PORT 1200 
#define BACKLOG 4 
struct sockaddr_in server; 
struct sockaddr_in client;
int sockfd,sockfd2,n_bytes; 
char msg[5000]; 

struct sockaddr_in servertwo; 
struct sockaddr_in clienttwo;
int sock_one,secondn_bytes,sock_two; 
char workmsg[5000];
#define workPORT 7777 
#define workBACKLOG 4 
void handle_error(void);

int main(){ 
WSADATA wsda; 
WSAStartup(0x0101,&wsda); 
	if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ 
	handle_error();
	printf("Socket error..."); 
	return 0; 
	} 

server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(PORT); 
server.sin_family=AF_INET; 

	if((sock_one=socket(AF_INET,SOCK_STREAM,0))==-1){ 
	handle_error();
	printf("Socket error..."); 
	return 0; 
	} 

servertwo.sin_addr.s_addr=INADDR_ANY; 
servertwo.sin_port=htons(workPORT); 
servertwo.sin_family=AF_INET; 

	if(bind(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ 
	handle_error();
	printf("Cannot bind..."); 
	return 0; 
	} 

	if(listen(sockfd,BACKLOG)){ /*Listening */
	handle_error();
	printf("Error Listening..."); 
	return 0; 
	} 

	if(bind(sock_one,(struct sockaddr*)&servertwo,sizeof(struct sockaddr))==-1){ 
	handle_error();
	printf("Cannot bind..."); 
	return 0; 
	} 

	if(listen(sock_one,workBACKLOG)){
	handle_error();
	printf("Error Listening..."); 
	return 0; 
	} 

	while (1){ 

	int size=sizeof(struct sockaddr_in); 
	int size2=sizeof(struct sockaddr_in); 

		if((sockfd2=accept(sockfd,(struct sockaddr*)&client,&size))==-1){ 
		handle_error();
		printf("Accept Error..."); 
		return 0; 
		} 

		if((n_bytes=recv(sockfd2,msg ,5000,0))==-1){ 
		handle_error();
		printf("Error Recv..."); 
		return 0; 
		} 

		if((sock_two=accept(sock_one,(struct sockaddr*)&clienttwo,&size2))==-1){ 
		handle_error();
		printf("Accept Error..."); 
		return 0; 
		} 

		if((secondn_bytes=recv(sock_two,workmsg ,5000,0))==-1){ 
		handle_error();
		printf("Error Recv..."); 
		return 0; 
		} 

	msg[n_bytes]='\0'; 
	workmsg[secondn_bytes]='\0'; 

	printf("Client 1's Message:%s",msg); 
	printf("Client 2's Message:%s",workmsg); 
	} 

WSACleanup(); 
closesocket(sockfd);
closesocket(sockfd2); 
closesocket(sock_one); 
closesocket(sock_two); 
return 0; 

} 

void handle_error(void)
{
  switch ( WSAGetLastError() )
  {
    case WSANOTINITIALISED :
      printf("Unable to initialise socket.\n");
    break;
    case WSAEAFNOSUPPORT :
      printf("The specified address family is not supported.\n");
    break;
    case WSAEADDRNOTAVAIL :
      printf("Specified address is not available from the local machine.\n");
    break;
    case WSAECONNREFUSED :
      printf("The attempt to connect was forcefully rejected.\n"); 
      break; 
    case WSAEDESTADDRREQ : 
      printf("address destination address is required.\n");
    break;
    case WSAEFAULT :
      printf("The namelen argument is incorrect.\n");
    break;
    case WSAEINVAL :
      printf("The socket is not already bound to an address.\n");
    break;
    case WSAEISCONN :
      printf("The socket is already connected.\n");
    break;
    case WSAEADDRINUSE :
      printf("The specified address is already in use.\n");
    break;
    case WSAEMFILE : 
      printf("No more file descriptors are available.\n");
    break;
    case WSAENOBUFS :
      printf("No buffer space available. The socket cannot be created.\n");
    break;
    case WSAEPROTONOSUPPORT :
      printf("The specified protocol is not supported.\n");
      break; 
    case WSAEPROTOTYPE :
      printf("The specified protocol is the wrong type for this socket.\n");
    break;
    case WSAENETUNREACH : 
      printf("The network can't be reached from this host at this time.\n");
    break; 
    case WSAENOTSOCK :
       printf("The descriptor is not a socket.\n");
    break;
    case WSAETIMEDOUT :
      printf("Attempt timed out without establishing a connection.\n");
    break;
    case WSAESOCKTNOSUPPORT :
       printf("Socket type is not supported in this address family.\n");
    break;
    case WSAENETDOWN :
      printf("Network subsystem failure.\n");
    break;
    case WSAHOST_NOT_FOUND :
      printf("Authoritative Answer Host not found.\n");
    break;
    case WSATRY_AGAIN :
      printf("Non-Authoritative Host not found or SERVERFAIL.\n");
     break;
    case WSANO_RECOVERY :
       printf("Non recoverable errors, FORMERR, REFUSED, NOTIMP.\n");
    break;
    case WSANO_DATA :
      printf("Valid name, no data record of requested type.\n");
    break;
      case WSAEINPROGRESS :
      printf("address blocking Windows Sockets operation is in progress.\n");
    break;
    case WSAEINTR :
      printf("The (blocking) call was canceled via WSACancelBlockingCall().\n");
    break;
    default :
      printf("Unknown error.\n");
     break;
  }

}

now the problem when i run the program and try to send a message it does nothing. it does not display the message sent or display some error ( if any ).

can anyone help me shed light to this, or better yet give me a link in "How to listens to two different ports at the same time using C" i've tried to google it but the results a not that promising.

sorry for the long post.
any comment will be much appreciated

btw: i'm using mvc 6 and win2k

thanks in advance,
jaro
  #2  
Old 30-Dec-2005, 04:54
kobi_hikri's Avatar
kobi_hikri kobi_hikri is offline
Regular Member
 
Join Date: Apr 2005
Location: Israel
Posts: 431
kobi_hikri has a spectacular aura aboutkobi_hikri has a spectacular aura about

Re: How to listens to two different ports at the same time


It compiles ok, but when trying to build the code, I get :

Code:
Compiling... socket.cpp Linking... socket.obj : error LNK2001: unresolved external symbol _closesocket@4 socket.obj : error LNK2001: unresolved external symbol _WSACleanup@0 socket.obj : error LNK2001: unresolved external symbol _recv@16 socket.obj : error LNK2001: unresolved external symbol _accept@12 socket.obj : error LNK2001: unresolved external symbol _listen@8 socket.obj : error LNK2001: unresolved external symbol _bind@12 socket.obj : error LNK2001: unresolved external symbol _htons@4 socket.obj : error LNK2001: unresolved external symbol _socket@12 socket.obj : error LNK2001: unresolved external symbol _WSAStartup@8 socket.obj : error LNK2001: unresolved external symbol _WSAGetLastError@0 Debug/socket.exe : fatal error LNK1120: 10 unresolved externals Error executing link.exe. socket.exe - 11 error(s), 0 warning(s)

Anyway, here is an example for working with sockets Dave posted :

CPP / C++ / C Code:

/* example of reading a web page from a server
 *
 * The contents of the page are written to stdout.
 *
 * I have used stderr for all messages that are not part of the page
 * that was accessed so that you can capture the page output by
 * redirecting stdout to a file.
 *
 * This was compiled by Borland bcc32 version 5.5.1
 * October, 2005
 *
 * I also compiled with Microsoft Visual C++ version 6.0
 * (With Microsoft, you have to explicitly link in the wsock32 library)
 *
 * The example was adapted from a UNIX-based example given in a thread
 * on the C/C++ Programming Forum at gidforums.
 *
 * [url]http://www.gidforums.com/t-7429.html[/url]
 *
 * I am not aware of any copyright that applies to the original example.
 * No restrictions are added here.
 *
 * davekw7x, member, gidforums.com
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
#include <string.h>
#include <io.h>

/* 
 * For Borland, the following definition is required to get the
 * prototype for inet_ntoa()
 */
#define INCL_WINSOCK_API_PROTOTYPES 1

int main (int argc, char* const argv[])
{
  void get_home_page (int socket_fd);

  int socket_fd;
  struct sockaddr_in name = {0};
  struct hostent* hostinfo;

  /* 
   * The WSA stuff is need for Microsoft Windows socket programming.
   * Don't worry about it: treat it as an idiom.
   */

  WSADATA wsadata;

  if (argc < 2) {
    fprintf(stderr, "You must supply a URL.\n");
    fprintf(stderr, "It can be a name:     myhost.com\n");
    fprintf(stderr, "     or\n");
    fprintf(stderr, "It can be a quad-dot: 192.168.0.1\n");
    return 0;
  }

  fprintf(stderr, "The program will attempt to access the page at %s\n", 
         argv[1]);


  /* Get a socket descriptor from the operating system */

  WSAStartup(MAKEWORD(1,1), &wsadata);

  socket_fd = socket(PF_INET, SOCK_STREAM, 0);

  if (socket_fd < 0) {
    perror("socket");
    WSACleanup();
    return 1;
  }

  name.sin_family = PF_INET;

  /*
   * Convert from strings to numbers.
   * Input can be a URL name, like myhost.com, or 
   * a quad-dot value like 192.168.0.1
   */

  hostinfo = gethostbyname (argv[1]);

  if (hostinfo == NULL) {
    fprintf(stderr, "Can't get hostinfo for <%s>\n", argv[1]);
    WSACleanup();
    return 1;
  }

  /* 
   * Use the cast to prevent compiler warnings.
   * This is legal: trust me.
   * (Just joking, of course: trust no one, but it really is valid;
   *  check it out.)
   */

  name.sin_addr = *((struct in_addr *)hostinfo->h_addr);

  /* 
   * just for kicks, print the address in quad-dot format
   */
  fprintf(stderr, "The URL is %s\n", inet_ntoa(name.sin_addr));

  /* Web servers use port 80. */
  name.sin_port = htons (80);

  /* Connect to the Web server */
  if (connect (socket_fd, (struct sockaddr *)&name, sizeof (struct sockaddr)) == -1) {
    perror ("connect");
    WSACleanup();
    return 1;
  }
  fprintf(stderr, "Connect OK\n");

  /* Retrieve the server’s home page. */
  get_home_page (socket_fd);

  WSACleanup();
  return 0;
}


/* Print the contents of the home page for the server’s socket */

void get_home_page (int socket_fd)
{
  char buffer[10000] = {0};

  int number_characters_read;
  int number_chars_written;

  /* Send the HTTP GET command for the home page. */
  sprintf (buffer, "GET /\n");
  if (send(socket_fd, buffer, strlen (buffer), 0) < 0) {
    perror("write");
    return;
  }

  /* Read from the socket. The call to read may not
   * return all the data at one time, so keep
   * trying until we run out.
   */
  while (1) {
    number_characters_read = recv(socket_fd, buffer, sizeof(buffer), 0);
    if (number_characters_read == 0) {
      return;
    }

    /* Write the data to standard output.
     *
     * Note that the recv() function does not put the terminating null
     * after the bytes read, so, don't use printf("%s") here unless you have
     * taken care of that little detail. (Same warning for strcpy() or other
     * other C standard library string functions.)
     */
    fwrite (buffer, sizeof (char), number_characters_read, stdout);
  }
}


It demonstrates working with sockets in a simple way.
I posted this example Dave wrote for the benefit of all. I hope it will help you.

Kobi.
__________________
It's actually a one time thing (it just happens alot).
  #3  
Old 01-Jan-2006, 23:09
jaro's Avatar
jaro jaro is offline
Junior Member
 
Join Date: Nov 2005
Location: somewhere in souteast asia
Posts: 59
jaro will become famous soon enough

Re: How to listens to two different ports at the same time


Quote:
Originally Posted by kobi_hikri
It compiles ok, but when trying to build the code, I get :

Code:
Compiling... socket.cpp Linking... socket.obj : error LNK2001: unresolved external symbol _closesocket@4 socket.obj : error LNK2001: unresolved external symbol _WSACleanup@0 socket.obj : error LNK2001: unresolved external symbol _recv@16 socket.obj : error LNK2001: unresolved external symbol _accept@12 socket.obj : error LNK2001: unresolved external symbol _listen@8 socket.obj : error LNK2001: unresolved external symbol _bind@12 socket.obj : error LNK2001: unresolved external symbol _htons@4 socket.obj : error LNK2001: unresolved external symbol _socket@12 socket.obj : error LNK2001: unresolved external symbol _WSAStartup@8 socket.obj : error LNK2001: unresolved external symbol _WSAGetLastError@0 Debug/socket.exe : fatal error LNK1120: 10 unresolved externals Error executing link.exe. socket.exe - 11 error(s), 0 warning(s)

oops forgot to tell that you should include WINSOCK32.LIB in the project and in the project setting under code generaton set run time library to Multithreaded...
  #4  
Old 02-Jan-2006, 06:52
jaro's Avatar
jaro jaro is offline
Junior Member
 
Join Date: Nov 2005
Location: somewhere in souteast asia
Posts: 59
jaro will become famous soon enough

Re: How to listens to two different ports at the same time


finally found the solution...
although the program sometimes hungs when i try to exit it...
anyways thats fine with me...
btw here is the code
CPP / C++ / C Code:
#include <stdio.h>
#include <winsock.h> 
#include <process.h>

#define PORT 1200 
#define BACKLOG 4 
#define workPORT 7777 
#define workBACKLOG 4 
#define STRSIZE 16536
#define STRSIZETWO 16536

struct sockaddr_in server; 
struct sockaddr_in client;
int sockfd,sockfd2,n_bytes; 
char msg[5000]; 
struct sockaddr_in servertwo; 
struct sockaddr_in clienttwo;
int sock_one,secondn_bytes,sock_two; 
char workmsg[5000];

int recieveMessage(void);
int recieveMessageTwo(void);
void handle_error(void);

void errexit(const char *format, ...)
{
	va_list	args;
	va_start(args, format);
	vfprintf(stderr, format, args);
	va_end(args);
	WSACleanup();
	exit(1);
}


int main(){ 

WSADATA wsda; 
WSAStartup(0x0101,&wsda); 

	if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ 
	handle_error();
	printf("Socket error..."); 
	return 0; 
	} 

server.sin_addr.s_addr=INADDR_ANY; 
server.sin_port=htons(PORT); 
server.sin_family=AF_INET; 


	if((sock_one=socket(AF_INET,SOCK_STREAM,0))==-1){ 
	handle_error();
	printf("Socket error..."); 
	return 0; 
	} 

servertwo.sin_addr.s_addr=INADDR_ANY; 
servertwo.sin_port=htons(workPORT); 
servertwo.sin_family=AF_INET; 


	if(bind(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr))==-1){ 
	handle_error();
	printf("Cannot bind..."); 
	return 0; 
	} 


	if(bind(sock_one,(struct sockaddr*)&servertwo,sizeof(struct sockaddr))==-1){ 
	handle_error();
	printf("Cannot bind..."); 
	return 0; 
	} 

	if(listen(sockfd,BACKLOG)){ 
	handle_error();
	printf("Error Listening..."); 
	return 0; 
	} 

	if(listen(sock_one,workBACKLOG)){ 
	handle_error();
	printf("Error Listening..."); 
	return 0; 
	} 



	while (1){ 

		if (_beginthread((void (*)(void *)) recieveMessage, STRSIZE, ( void *) sockfd) < 0) 
			{ 
				handle_error();
				errexit("_beginthread: %s\n", strerror(errno));
			}

		if (_beginthread((void (*)(void *)) recieveMessageTwo, STRSIZETWO, ( void *) sock_one) < 0) 
			{ 
				handle_error();
				errexit("_beginthread: %s\n", strerror(errno));
			}

	} 


WSACleanup(); 
closesocket(sockfd); 
closesocket(sockfd2); 
closesocket(sock_one);
closesocket(sock_two); 

return 0; 
} 


int recieveMessage(){
	int size=sizeof(struct sockaddr_in); 

		if((sockfd2=accept(sockfd,(struct sockaddr*)&client,&size))==-1){ 
		printf("Accept Error..."); 
		} 

		if((n_bytes=recv(sockfd2,msg ,50,0))==-1){ 
		printf("Error Recv..."); 
		} 

		msg[n_bytes]='\0'; 

		printf("Client's Message:%s",msg); 

return 0; 
}


int recieveMessageTwo(){
	int size2=sizeof(struct sockaddr_in); 

		if((sock_two=accept(sock_one,(struct sockaddr*)&clienttwo,&size2))==-1){ 

		printf("Accept Error..."); 

		} 

		if((secondn_bytes=recv(sock_two,workmsg ,5000,0))==-1){ 

		printf("Error Recv..."); 

		} 

		workmsg[secondn_bytes]='\0'; 

		printf("Client 2's Message:%s",workmsg); 

return 0; 
}

void handle_error(void)
{
  switch ( WSAGetLastError() )
  {
    case WSANOTINITIALISED :
      printf("Unable to initialise socket.\n");
    break;
    case WSAEAFNOSUPPORT :
      printf("The specified address family is not supported.\n");
    break;
    case WSAEADDRNOTAVAIL :
      printf("Specified address is not available from the local machine.\n");
    break;
    case WSAECONNREFUSED :
      printf("The attempt to connect was forcefully rejected.\n"); 
      break; 
    case WSAEDESTADDRREQ : 
      printf("address destination address is required.\n");
    break;
    case WSAEFAULT :
      printf("The namelen argument is incorrect.\n");
    break;
    case WSAEINVAL :
      printf("The socket is not already bound to an address.\n");
    break;
    case WSAEISCONN :
      printf("The socket is already connected.\n");
    break;
    case WSAEADDRINUSE :
      printf("The specified address is already in use.\n");
    break;
    case WSAEMFILE : 
      printf("No more file descriptors are available.\n");
    break;
    case WSAENOBUFS :
      printf("No buffer space available. The socket cannot be created.\n");
    break;
    case WSAEPROTONOSUPPORT :
      printf("The specified protocol is not supported.\n");
      break; 
    case WSAEPROTOTYPE :
      printf("The specified protocol is the wrong type for this socket.\n");
    break;
    case WSAENETUNREACH : 
      printf("The network can't be reached from this host at this time.\n");
    break; 
    case WSAENOTSOCK :
       printf("The descriptor is not a socket.\n");
    break;
    case WSAETIMEDOUT :
      printf("Attempt timed out without establishing a connection.\n");
    break;
    case WSAESOCKTNOSUPPORT :
       printf("Socket type is not supported in this address family.\n");
    break;
    case WSAENETDOWN :
      printf("Network subsystem failure.\n");
    break;
    case WSAHOST_NOT_FOUND :
      printf("Authoritative Answer Host not found.\n");
    break;
    case WSATRY_AGAIN :
      printf("Non-Authoritative Host not found or SERVERFAIL.\n");
     break;
    case WSANO_RECOVERY :
       printf("Non recoverable errors, FORMERR, REFUSED, NOTIMP.\n");
    break;
    case WSANO_DATA :
      printf("Valid name, no data record of requested type.\n");
    break;
      case WSAEINPROGRESS :
      printf("address blocking Windows Sockets operation is in progress.\n");
    break;
    case WSAEINTR :
      printf("The (blocking) call was canceled via WSACancelBlockingCall().\n");
    break;
    default :
      printf("Unknown error.\n");
     break;
  }
}
i'm using vc6 and my os is win2k also include the WSOCK32.lib and make it multithreaded in the "USe run time Library"

any comment here will be much appreciated ( especially if you some wrong convention that i've used )

- jaro
  #5  
Old 06-Jan-2006, 03:23
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough

Re: How to listens to two different ports at the same time


Hi,

I just looked at your code. I have a doubt. Parden me if i am wrong. I am not a windows person. In your infinite while loop you are starting a new thread for each loop run. Arn't you suppose to start one thread for each socket and then in thread handler run an infinite loop to receive messages.? In your thread handler you are accepting on the socket passed as an argument. If I am right, you are creating thousands of unneccessary threads. All you need is 2 threads. You need to run accept and recv in infinite loop like below

CPP / C++ / C Code:
void recieveMessage ()
{
    int newfd;
    
    int size=sizeof(struct sockaddr_in); 
    while (1)
    {
        if((newfd=accept(sockfd,(struct sockaddr*)&client,&size))==-1)
        { 
	    printf("Accept Error..."); 
            break; /* Break out an infinite while loop to the end return stmt */
        } 

        if((n_bytes=recv(newfd,msg ,50,0))==-1)
        { 
            printf("Error Recv...");
            close(newfd); /* Some error happened in receive. Close the new socket */
            continue; /* Skip to go back up for the next accept() call */ 
        } 

        msg[n_bytes]='\0'; 

        printf("Client's Message:%s",msg); 
        
        close(newfd);    /* Close it once its job is done */
    }   
    
    return;
}

You dont have to write two different functions for each thread which essentially does the same job. You can use above function for both the threads. Just pass different socket discriptors to each thread while starting it.

Inside a thread, you can identify a thread by its Id. There are methods to retrieve this id. On *nix using POSIX threads (pthreads), function pthread_self() returns the thread id of the current thread. You can identify which thread received the message using this id. Or you can pass a data structure to the thread as an argument which will have information abt whether its a client or server thread alongwith the socket descriptor, which you can use inside the theread function to print the appropriate message.
  #6  
Old 06-Jan-2006, 06:36
jaro's Avatar
jaro jaro is offline
Junior Member
 
Join Date: Nov 2005
Location: somewhere in souteast asia
Posts: 59
jaro will become famous soon enough

Re: How to listens to two different ports at the same time


hi nkhambal,

thanks for your comment and for pointing out some things that i failed to see ... (now i know the reason why program slow down my system )

i'll make the necessary changes in my code and i will post it to this thread...

many thanks,
jaro
 
 

Recent GIDBlogMeeting the local Iraqis by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Creating a time converter tylerfelix C++ Forum 15 20-Nov-2005 20:34
Simulation Problem wu_weidong C++ Forum 7 12-Mar-2005 22:56
[CONTEST?]Data Structure Test dsmith C Programming Language 2 06-Jun-2004 15:13
time Problem zuzupus MySQL / PHP Forum 9 24-Jul-2003 07:02

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:30.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.