View Single Post
Old Aug 27th, 2005, 9:30 AM   #47
Brent
Highly Adaptive Penguin
 
Brent's Avatar
 
Join Date: May 2005
Location: United States
Posts: 251
Rep Power: 4 Brent is on a distinguished road
yeah thanks. i did what you said and made a multi person chat server.

here's the code
//multiperson chat server
//programmed by brent matthews

#include<iostream.h>
#include<winsock.h>
#pragma comment(lib,"wsock32.lib")
#include<string.h>

int main()
{
	WORD sock;
	WSADATA wsaData;
	sock=WSAStartup(0x0101,&wsaData);
	
	fd_set master;
	fd_set read_socks;
	fd_set write_socks;
	sockaddr_in sin;
	sockaddr_in dest;
	
	timeval tv;
	tv.tv_sec = 30; 
	tv.tv_usec = 500000; 
	
	int sock_max;
	int listener;
	int new_sock;
	char buf[512];
	int addrlen;
	int i,j;
	int nbytes;
	int yes=1;
	int yeslen=sizeof(yes);
	
	FD_ZERO(&master);
	FD_ZERO(&read_socks);
	
	if((listener=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
	{
		cout<<"invalid socket\n";
		WSACleanup();
		return 0;
	}
	
	if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, NULL,NULL) == SOCKET_ERROR) 
	{ 
		cout<<"setsockopt error\n";
	} 
	
	sin.sin_family=AF_INET;
	sin.sin_port=htons(8888);
	sin.sin_addr.s_addr=INADDR_ANY;
	
	if(bind(listener,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR)
	{
		cout<<"failed bind\n";
		WSACleanup();
		return 0;
	}
	
	if(listen(listener,10)==SOCKET_ERROR)
	{
		cout<<"failed listen\n";
		WSACleanup();
		return 0;
	}
	
	FD_SET(listener,&master);
	sock_max=listener;
	
	for(;;)
	{
		read_socks=master;
		write_socks=master;
		if(select(sock_max+1,&read_socks,NULL,NULL,&tv)==SOCKET_ERROR)
		{
			cout<<"select timed out\n";
			WSACleanup();
			return 0;
		}
		
		for(i=0;i<=sock_max;i++)
		{
			if(FD_ISSET(i,&read_socks))
			{
				if(i==listener)
				{
					addrlen=sizeof(dest);
					if((new_sock=accept(listener,NULL,NULL))==SOCKET_ERROR)
					{
						cout<<"failed accept\n";
						WSACleanup();
						return 0;
					}
					else
					{
						FD_SET(new_sock,&master);
						if(new_sock>sock_max)
						{
							sock_max=new_sock;
						}
						cout<<"new connection from: "<<new_sock<<", on: "<<inet_ntoa(dest.sin_addr)<<endl;
					}
				}
				else
				{
					if((nbytes=recv(i,buf,sizeof(buf),0))<=0)
					{
						if(nbytes==0)
						{
							cout<<"socket: "<<i<<" hung up\n";
							
						}
						else
						{
							cout<<"failed recv\n";
							WSACleanup();
							return 0;
						}
						closesocket(i);
						FD_CLR(i,&master);
					}
				}
			}
			else
			{
				for(j=0;j<=sock_max;j++)
				{
					if(FD_ISSET(j,&master))
					{
						if(j!=listener && j!=i)
						{
							if(send(j,buf,nbytes,0)==SOCKET_ERROR)
							{
								cout<<"failed send\n";
								WSACleanup();
								return 0;
							}
						}
					}
				}
			}
		}
	}
	return 0;
}

how is this?
and i have one more question: what type of sockets should i use for the client program?
Brent is offline   Reply With Quote