Exemple #1
0
void main(){

	CallDll();
	SocketStartup();//startup the WSA
	Listen();
}
DWORD CTcpServerSocketHelper::Start(ITcpServerSocketHelper_Event *pEvent,
									DWORD dwListenPort/*=0*/,BOOL bReadData/*=TRUE*/)
{
	DWORD dwResult = -1;
	DWORD threadID = 0;

	m_pEvent = pEvent;
	m_dwListenPort = dwListenPort;

	if (!CreateTcpSocket(TRUE))
	{
		dwResult = 1;
		goto Exit0;
	}

	BOOL bOpt = TRUE;
	::setsockopt (m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&bOpt, sizeof (bOpt));

	if (!Bind())
	{
		dwResult = 2;
		goto Exit0;
	}

	if (!Listen())
	{
		dwResult = 3;
		goto Exit0;
	}

	m_hTerminateAcceptThreadEvent = ::CreateEvent(NULL, TRUE, FALSE,NULL);
	if (!m_hTerminateAcceptThreadEvent)
	{
		dwResult = 4;
		goto Exit0;
	}

	m_hAcceptThreadHandle = (HANDLE)::CreateThread( NULL, 0, 
		(LPTHREAD_START_ROUTINE)_AcceptThreadProc, this, 0, &threadID );
	if (!m_hAcceptThreadHandle)
	{
		dwResult = 5;
		goto Exit0;
	}


	if (bReadData)
	{
		m_hTerminateReadDataThreadEvent = ::CreateEvent(NULL, TRUE, FALSE,NULL);
		if (!m_hTerminateReadDataThreadEvent)
		{
			dwResult = 6;
			goto Exit0;
		}

		m_hReadDataThreadHandle = (HANDLE)::CreateThread( NULL, 0, 
			(LPTHREAD_START_ROUTINE)_ReadDataThreadProc, this, 0, &threadID );
		if (!m_hReadDataThreadHandle)
		{
			goto Exit0;
		}
	}

	dwResult = 0;
Exit0:
	if (0 != dwResult)
	{
		Stop();
	}

	if (dwResult == 0)
	{
		return m_dwListenPort;
	}
	return (DWORD)-1;
}
Exemple #3
0
// MAIN
int main(int argc, char **argv) {
   // Local variables
   int pid;
   int port;
   int listenfd;
   int connfd;
   struct sockaddr_in clientAddr;
   socklen_t clientSize = sizeof(clientAddr);
   FILE* logFile;

   // gets port number
   if(argc == 2) {
      port = atoi(argv[1]);
   } else {
      perror("Invalid arguments.");
      exit(1);
   }

   // opens log file
   logFile = fopen("log.txt", "a+");

   // creates listen socket
   listenfd = listenSocket(port);

   // starts listening
   Listen(listenfd, LISTENQUEUE); 

   for ( ; ; ) {
      // accepts a connection
      connfd = Accept(listenfd, (struct sockaddr *)&clientAddr, &clientSize);

      // prints the info
      PrintConnectionInfo(clientAddr);

      // log
      logConnection(logFile, clientAddr);

      // fork
      if((pid = fork()) == 0) {
         // child process closes the listen socket
         close(listenfd);
         
         // process
         process(connfd, clientAddr);
         
         // child process closes the connection
         close(connfd); 

         // prints info of disconnection
         printDisconnectInfo(clientAddr);

         // log
         logDisconnection(logFile, clientAddr);

         // finished execution
         exit(0); 
      }

      // parent process closes the connection with client
      close(connfd);
   }

   // closes log file
   fclose(logFile);

   return(0);
}
Exemple #4
0
//!! textbook p146 ch 6.11 poll 模板
int
main(int argc, char **argv)
{
    int                 i, maxi, listenfd, connfd, sockfd;
    int                 nready;
    ssize_t             n;
    char                buf[MAXLINE];
    socklen_t           clilen;
    struct pollfd       client[OPEN_MAX];
    struct sockaddr_in  cliaddr, servaddr;

    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family      = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port        = htons(SERV_PORT);

    Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

    Listen(listenfd, LISTENQ);

    client[0].fd = listenfd;
    client[0].events = POLLRDNORM;
    for (i = 1; i < OPEN_MAX; i++)
        client[i].fd = -1;      /* -1 indicates available entry */
    maxi = 0;                   /* max index into client[] array */
/* end fig01 */

/* include fig02 */
    for ( ; ; ) {
        nready = Poll(client, maxi+1, INFTIM);

        if (client[0].revents & POLLRDNORM) {   /* new client connection */
            clilen = sizeof(cliaddr);
            connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef  NOTDEF
            printf("new client: %s\n", Sock_ntop((SA *) &cliaddr, clilen));
#endif

            for (i = 1; i < OPEN_MAX; i++)
                if (client[i].fd < 0) {
                    client[i].fd = connfd;  /* save descriptor */
                    break;
                }
            if (i == OPEN_MAX)
                err_quit("too many clients");

            client[i].events = POLLRDNORM;
            if (i > maxi)
                maxi = i;               /* max index in client[] array */

            if (--nready <= 0)
                continue;               /* no more readable descriptors */
        }

        for (i = 1; i <= maxi; i++) {   /* check all clients for data */
            if ( (sockfd = client[i].fd) < 0)
                continue;
            if (client[i].revents & (POLLRDNORM | POLLERR)) {
                if ( (n = read(sockfd, buf, MAXLINE)) < 0) {
                    if (errno == ECONNRESET) {
                            /*4connection reset by client */
#ifdef  NOTDEF
                        printf("client[%d] aborted connection\n", i);
#endif
                        Close(sockfd);
                        client[i].fd = -1;
                    } else
                        err_sys("read error");
                } else if (n == 0) {
                        /*4connection closed by client */
#ifdef  NOTDEF
                    printf("client[%d] closed connection\n", i);
#endif
                    Close(sockfd);
                    client[i].fd = -1;
                } else
                    Writen(sockfd, buf, n);

                if (--nready <= 0)
                    break;              /* no more readable descriptors */
            }
        }
    }
}
Exemple #5
0
// Management port Listen thread
void NiListenThread(THREAD *thread, void *param)
{
	NAT *n = (NAT *)param;
	SOCK *a;
	UINT i;
	bool b = false;
	// Validate arguments
	if (thread == NULL || param == NULL)
	{
		return;
	}

	// Initialize the management list
	n->AdminList = NewList(NULL);

	while (true)
	{
		a = Listen(DEFAULT_NAT_ADMIN_PORT);
		if (b == false)
		{
			b = true;
			NoticeThreadInit(thread);
		}
		if (a != NULL)
		{
			break;
		}

		Wait(n->HaltEvent, NAT_ADMIN_PORT_LISTEN_INTERVAL);
		if (n->Halt)
		{
			return;
		}
	}

	n->AdminListenSock = a;
	AddRef(a->ref);

	// Waiting
	while (true)
	{
		SOCK *s = Accept(a);
		THREAD *t;
		NAT_ADMIN *admin;
		if (s == NULL)
		{
			break;
		}
		if (n->Halt)
		{
			ReleaseSock(s);
			break;
		}

		admin = ZeroMalloc(sizeof(NAT_ADMIN));
		admin->Nat = n;
		admin->Sock = s;
		t = NewThread(NiAdminThread, admin);
		WaitThreadInit(t);
		ReleaseThread(t);
	}

	// Disconnect all management connections
	LockList(n->AdminList);
	{
		for (i = 0;i < LIST_NUM(n->AdminList);i++)
		{
			NAT_ADMIN *a = LIST_DATA(n->AdminList, i);
			Disconnect(a->Sock);
			WaitThread(a->Thread, INFINITE);
			ReleaseThread(a->Thread);
			ReleaseSock(a->Sock);
			Free(a);
		}
	}
	UnlockList(n->AdminList);

	ReleaseList(n->AdminList);

	ReleaseSock(a);
}
Exemple #6
0
int main(int argc, char **argv)
{
    int i, maxi, listenfd, connfd, sockfd;
	int nready;
	ssize_t n;
	char buf[MAXLINE];
	socklen_t clilen;
	struct pollfd client[OPEN_MAX];
	struct sockaddr_in cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	client[0].fd = listenfd;
	client[0].events = POLLIN;
	for (i = 1; i < OPEN_MAX; i++)
		client[1].fd = -1;
	maxi = 0;

	for ( ; ; )
	{
		nready = Poll(client, maxi + 1, INFTIM);

		if (client[0].revents & POLLIN)   /* new client connection */
		{
            clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *)&cliaddr, &clilen);

			for (i = 1; i < OPEN_MAX; i++)
				if (client[i].fd < 0)
				{
					client[i].fd = connfd;   /* save descriptor */
					break;
				}

			if (i == OPEN_MAX)
                err_quit("too many clients");
            
			client[i].events = POLLIN;
			if (i > maxi)
				maxi = i;   /* max index in client[] array */

			if (--nready <= 0)
				continue;   /* no more readable descriptors */
		}

		for (i = 1; i <= maxi; i++)   /* check all clients for data */
		{
            if ((sockfd = client[i].fd) < 0)
				continue;

			if (client[i].revents & (POLLIN | POLLERR))
			{
				if ((n = read(sockfd, buf, MAXLINE)) < 0)
				{
					if (errno == ECONNRESET)   /* connection reset by client */
					{
                        Close(sockfd);
						client[i].fd = -1;
					}
					else
						err_sys("read error");
				}
				else if (n == 0)   /* connection closed by client */
				{
					Close(sockfd);
					client[i].fd = -1;
				}
				else
				    Writen(sockfd, buf, n);

				if (--nready <= 0)   /* no more readable descriptors */
					break;
			}
		}
	}
}
Exemple #7
0
/* We can write a simple version of a TCP daytime server, which will work
 * with the daytime client.
 *
 * TCP服务器端一般要执行的步骤是: socket()->填充结构体(协议类型,本机ip地址,
 * 本机端口)->bind()->listen()->accept()->使用连接描述符进行读写.
 * TCP客户端一般要执行的步骤是: socket()->填充结构体(协议类型,服务器ip地址,
 * 服务器已知端口)->connect()
 */
int main(void)
{
    int listenfd, connfd;
    struct sockaddr_in servaddr;
    char buf[BUFSIZ];
    time_t ticks;

    /* 1. Create a TCP socket */
    listenfd = Socket(AF_INET, SOCK_STREAM, 0);

    /* 2. Bind server's well-known port to socket
     * The server's well-known port (13 for the daytime service) is bound
     * to the socket by filling in an Internet socket address structure and
     * calling bind(). We specify the IP address as INADDR_ANY, which allows
     * the server to accept a client connection on any interface, in case
     * the server host has multiple interfaces.
     *
     * 以普通用户运行该程序时,会报错: bind error: Permission denied
     * 此时,错误码是EACCES. 查看man bind手册,对该错误码解释为:
     * EACCES The address is protected, and the user is not the superuser.
     *
     * 在Linux中,只有 root 用户可以绑定 1024 以下的端口.
     * 查看 man 7 ip 手册,里面有如下说明:
     * The port numbers below 1024 are called privileged ports (or
     * sometimes: reserved ports). Only privileged processes (i.e., those
     * having the CAP_NET_BIND_SERVICE capability) may bind to these sockets
     * 所以运行该程序时,要用root用户或者sudo命令来运行.
     * 另外, 13 这个端口可能被占用导致绑定不成功. Linux下,查看端口是否被占
     * 用的方法是: netstat -apn | grep <端口号>. 例如: netstat -apn|grep 13
     */
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(13);
    Bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    /* 3. Convert socket to listening socket
     * By calling listen(), the socket is converted into a listening socket,
     * on which incomming connections from clients will be accepted by the
     * kernel. These three steps, socket(), bind(), and listen(), are the
     * normal steps for any TCP server to prepare what we call the listening
     * descriptor (listenfd in this example).
     */
    Listen(listenfd, LISTENQ);

    for (; ;) {
        /* 4. Accept client connection, send reply
         * Normally, the server process is put to sleep in the call to
         * accept(), waiting for a client connection to arrive and be
         * accepted. A TCP connection uses what is called a three-way
         * handshake to establish a connection. When this handshake
         * completes, accept() returns, and the return value from the
         * function is a new descriptor (connfd) that is called the
         * connected descriptor. This new descriptor is used for
         * communication with the new client. A new descriptor is returned
         * by accept() for each client that connects to our server.
         */
        connfd = Accept(listenfd, NULL, NULL);

        /* The current time and date are returned by the library function
         * time(), which returns the number of seconds since the Unix
         * Eproch: 00:00:00 January 1, 1970, Coordinated Universal Time(UTC)
         * The next library function, ctime(), converts this integer value
         * into a human-readable string sush as: Mon May 26 20:58:40 2003
         */
        ticks = time(NULL);
        snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&ticks));
        Write(connfd, buf, strlen(buf));

        /* 5. Terminate connection
         * The server closes its connection with the client by calling
         * close(). This initiates the normal TCP connection termination
         * sequence: a FIN is sent in each direction and each FIN is
         * acknowledged by the other end.
         */
        Close(connfd);
    }

    return 0;
}
//bool CListenSocket::StartListening()
//{
//	bListening = true;
//
//	// Creating the socket with SO_REUSEADDR may solve LowID issues if emule was restarted
//	// quickly or started after a crash, but(!) it will also create another problem. If the
//	// socket is already used by some other application (e.g. a 2nd emule), we though bind
//	// to that socket leading to the situation that 2 applications are listening at the same
//	// port!
//	if (!Create(thePrefs.GetPort(), SOCK_STREAM, FD_ACCEPT, CT2CA(theApp.GetBindAddress()), FALSE/*bReuseAddr*/)) // Added by thilon on 2006.10.18, for [BindToAdapter]
//		return false;
//
//	// Rejecting a connection with conditional WSAAccept and not using SO_CONDITIONAL_ACCEPT
//	// -------------------------------------------------------------------------------------
//	// recv: SYN
//	// send: SYN ACK (!)
//	// recv: ACK
//	// send: ACK RST
//	// recv: PSH ACK + OP_HELLO packet
//	// send: RST
//	// --- 455 total bytes (depending on OP_HELLO packet)
//	// In case SO_CONDITIONAL_ACCEPT is not used, the TCP/IP stack establishes the connection
//	// before WSAAccept has a chance to reject it. That's why the remote peer starts to send
//	// it's first data packet.
//	// ---
//	// Not using SO_CONDITIONAL_ACCEPT gives us 6 TCP packets and the OP_HELLO data. We
//	// have to lookup the IP only 1 time. This is still way less traffic than rejecting the
//	// connection by closing it after the 'Accept'.
//
//	// Rejecting a connection with conditional WSAAccept and using SO_CONDITIONAL_ACCEPT
//	// ---------------------------------------------------------------------------------
//	// recv: SYN
//	// send: ACK RST
//	// recv: SYN
//	// send: ACK RST
//	// recv: SYN
//	// send: ACK RST
//	// --- 348 total bytes
//	// The TCP/IP stack tries to establish the connection 3 times until it gives up. 
//	// Furthermore the remote peer experiences a total timeout of ~ 1 minute which is
//	// supposed to be the default TCP/IP connection timeout (as noted in MSDN).
//	// ---
//	// Although we get a total of 6 TCP packets in case of using SO_CONDITIONAL_ACCEPT,
//	// it's still less than not using SO_CONDITIONAL_ACCEPT. But, we have to lookup
//	// the IP 3 times instead of 1 time.
//
//	//if (thePrefs.GetConditionalTCPAccept() && !thePrefs.GetProxySettings().UseProxy) {
//	//	int iOptVal = 1;
//	//	VERIFY( SetSockOpt(SO_CONDITIONAL_ACCEPT, &iOptVal, sizeof iOptVal) );
//	//}
//
//	if (!Listen())
//		return false;
//
//	m_port = thePrefs.GetPort();
//
//	//// Added by thilon on 2006.10.19, for IFWS - [ICSFirewall]
//	//if(thePrefs.GetICFSupport())
//	//{
//	//	bool bResult = (theApp.m_pFirewallOpener->OpenPort(m_port, NAT_PROTOCOL_TCP, EMULE_DEFAULTRULENAME_TCP, thePrefs.GetICFClearOnClose() /*|| thePrefs.GetUseRandomPorts()*/));
//	//	theApp.QueueLogLine(false, GetResString(bResult ? IDS_FO_TEMPTCP_S : IDS_FO_TEMPTCP_F), m_port);
//	//}
//
//	if(mapping)
//	{
//		theApp.RemoveUPnPNatPort(mapping);
//	}
//
//	if(thePrefs.GetUPnPNat())
//	{
//		mapping = new CUPnP::UPNPNAT_MAPPING;
//		mapping->ref = &mapping;
//
//		mapping->internalPort = mapping->externalPort = thePrefs.GetPort();
//		mapping->protocol = CUPnP::UNAT_TCP;
//		mapping->description = "TCP Port";
//		if(theApp.AddUPnPNatPort(mapping, thePrefs.GetUPnPNatTryRandom()))
//			thePrefs.SetUPnPTCPExternal(mapping->externalPort);
//	}
//	/*else
//	{
//		thePrefs.SetUPnPTCPExternal(thePrefs.GetPort());
//	}*/
//
//	bListening = true;
//	return true;
//}
//upnp_end
bool CListenSocket::StartListening()
{
	//ADDED by fengwen on 2007/03/21	<begin> :	·ÀÖ¹Öظ´Create
	if (bPortListening)
		return true;
	//ADDED by fengwen on 2007/03/21	<end> :		·ÀÖ¹Öظ´Create	

	// Creating the socket with SO_REUSEADDR may solve LowID issues if emule was restarted
	// quickly or started after a crash, but(!) it will also create another problem. If the
	// socket is already used by some other application (e.g. a 2nd emule), we though bind
	// to that socket leading to the situation that 2 applications are listening at the same
	// port!
	if (!Create(thePrefs.GetPort(), SOCK_STREAM, FD_ACCEPT, thePrefs.GetBindAddrA(), FALSE/*bReuseAddr*/))
		return false;

	// Rejecting a connection with conditional WSAAccept and not using SO_CONDITIONAL_ACCEPT
	// -------------------------------------------------------------------------------------
	// recv: SYN
	// send: SYN ACK (!)
	// recv: ACK
	// send: ACK RST
	// recv: PSH ACK + OP_HELLO packet
	// send: RST
	// --- 455 total bytes (depending on OP_HELLO packet)
	// In case SO_CONDITIONAL_ACCEPT is not used, the TCP/IP stack establishes the connection
	// before WSAAccept has a chance to reject it. That's why the remote peer starts to send
	// it's first data packet.
	// ---
	// Not using SO_CONDITIONAL_ACCEPT gives us 6 TCP packets and the OP_HELLO data. We
	// have to lookup the IP only 1 time. This is still way less traffic than rejecting the
	// connection by closing it after the 'Accept'.

	// Rejecting a connection with conditional WSAAccept and using SO_CONDITIONAL_ACCEPT
	// ---------------------------------------------------------------------------------
	// recv: SYN
	// send: ACK RST
	// recv: SYN
	// send: ACK RST
	// recv: SYN
	// send: ACK RST
	// --- 348 total bytes
	// The TCP/IP stack tries to establish the connection 3 times until it gives up. 
	// Furthermore the remote peer experiences a total timeout of ~ 1 minute which is
	// supposed to be the default TCP/IP connection timeout (as noted in MSDN).
	// ---
	// Although we get a total of 6 TCP packets in case of using SO_CONDITIONAL_ACCEPT,
	// it's still less than not using SO_CONDITIONAL_ACCEPT. But, we have to lookup
	// the IP 3 times instead of 1 time.

	//if (thePrefs.GetConditionalTCPAccept() && !thePrefs.GetProxySettings().UseProxy) {
	//	int iOptVal = 1;
	//	VERIFY( SetSockOpt(SO_CONDITIONAL_ACCEPT, &iOptVal, sizeof iOptVal) );
	//}

	if (!Listen())
		return false;
	
	m_port = thePrefs.GetPort();
	bPortListening = true;
	bListening = true;

	return true;
}
Exemple #9
0
int
main(int argc, char **argv)
{
	int sock_fd,msg_flags;
	char readbuf[BUFFSIZE];
	struct sockaddr_in servaddr, cliaddr;
	struct sctp_sndrcvinfo sri;
	struct sctp_event_subscribe evnts;
	int stream_increment=1;
	socklen_t len;
	size_t rd_sz;

	if (argc == 2)
		stream_increment = atoi(argv[1]);
        sock_fd = Socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);

	Bind(sock_fd, (SA *) &servaddr, sizeof(servaddr));
	
/* include mod_serv06 */
	bzero(&evnts, sizeof(evnts));
	evnts.sctp_data_io_event = 1;
	evnts.sctp_association_event = 1;
	evnts.sctp_address_event = 1;
	evnts.sctp_send_failure_event = 1;
	evnts.sctp_peer_error_event = 1;
	evnts.sctp_shutdown_event = 1;
	evnts.sctp_partial_delivery_event = 1;
#ifdef UN_MOD
	evnts.sctp_adaptation_layer_event = 1;
#else
	evnts.sctp_adaption_layer_event = 1;
#endif
	Setsockopt(sock_fd, IPPROTO_SCTP, SCTP_EVENTS,
		   &evnts, sizeof(evnts));

	Listen(sock_fd, LISTENQ);
	printf("Start waiting...\n");
	for ( ; ; ) {
		len = sizeof(struct sockaddr_in);
		rd_sz = Sctp_recvmsg(sock_fd, readbuf, sizeof(readbuf),
			     (SA *)&cliaddr, &len,
			     &sri,&msg_flags);
		if(msg_flags & MSG_NOTIFICATION) {	// 表示收到一個事件,而非一個資料
			print_notification(readbuf);
			continue;
		}
/* end mod_serv06 */
		if(stream_increment) {
			sri.sinfo_stream++;
			// getsockopt用在sctp有問題!!先跳過!
			// if(sri.sinfo_stream >= sctp_get_no_strms(sock_fd,(SA *)&cliaddr, len)) 
			if(sri.sinfo_stream >= 100)
				sri.sinfo_stream = 0;
		}
		Sctp_sendmsg(sock_fd, readbuf, rd_sz, 
			     (SA *)&cliaddr, len,
			     sri.sinfo_ppid,
			     sri.sinfo_flags,
			     sri.sinfo_stream,
			     0, 0);
	}
}
 MidiInputDeviceMme::MidiInputDeviceMme(std::map<String,DeviceCreationParameter*> Parameters, void* pSampler) : MidiInputDevice(Parameters, pSampler) {
     AcquirePorts(((DeviceCreationParameterInt*)Parameters["PORTS"])->ValueAsInt());
     if (((DeviceCreationParameterBool*)Parameters["ACTIVE"])->ValueAsBool()) {
         Listen();
     }
 }
int main(int argc, char** argv) {

	SOCKET s, s_acceptor;  			  		// socket and acceptor socket
	struct sockaddr_in saddr, caddr;  // server and client address structures
	uint16_t lport_n, lport_h; 				// server port number by htons()
	int backlog = 2;									// pending requests queue length
	socklen_t caddr_len;							// client address length
	int retValue;											// service() returning status
	int i;
	
	/* Check number of arguments */
	checkArg(argc, 3);
	
	/* The number of children */
	n_children = atoi(argv[2]);
	if (n_children > 10) {
		fprintf(stderr, "- ERROR. Children must be at most 10.\n");
		return -1;
	}
	
	/* Alloc memory for pids */
	pids = (pid_t*)malloc(n_children*sizeof(pid_t));
	if (pids == NULL) {
		fprintf(stderr, "- ERROR allocating pids.\n");
		return -1;
	}
	
	/* Instantiate a signal handler for SIGINT */
	Signal(SIGINT, sigintHandler);

	/* Initialize the socket API (only for Windows) */
	SockStartup();

	/* Set port number  */
	lport_n = setPortarg(argv[1], &lport_h);

	/* Create the socket */
	fprintf(stdout, "Creating the socket...\n");
	s = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	fprintf(stdout, "- OK. Socket fd: %d\n", s);
	
	/* Prepare server address structure */
	saddr.sin_family = AF_INET;
	saddr.sin_port = lport_n;
	saddr.sin_addr.s_addr = INADDR_ANY;

	/* Bind the socket to a local network address */
	fprintf(stdout, "Binding the socket...\n");
	Bind(s, (struct sockaddr*) &saddr, sizeof(saddr));
	fprintf(stdout, "- OK. Socket bound.\n");

	/* Listen to connection requests */
	fprintf(stdout, "Listen at socket %d with backlog = %d...\n", s, backlog);
	Listen(s, backlog);
	fprintf(stdout, "- OK. Socket is listening on ");
	showAddress(&saddr);
	
	for (i=0; i<n_children; i++) {
		
		if ((pids[i] = fork()) < 0) {
			fprintf(stderr, "- ERROR. fork() failed.\n");
		} else if ((pids[i]) > 0) {
			// The parent
		} else {
			// The child
			while(1) {
				/* Accept connection requests */
				br();
				caddr_len = sizeof(struct sockaddr_in);
				s_acceptor = Accept(s, (struct sockaddr*) &caddr, &caddr_len);
				fprintf(stdout, "- New connection from client ");
				showAddress(&caddr);
				
				retValue = service(s_acceptor);
				
				closesocket(s_acceptor);
				fprintf(stdout, "--- Connection closed by %s", (retValue == 0) ? "client\n" : "server\n");
				br();
			}
		}
		
	}
	
	while(1) {
		pause();
	}
	
	return 0;
}
Exemple #12
0
PlayField::PlayField(Hiscore *h, View *parent, ScrollText *st) : View(Rect(0,0,1,1)), Message(){ //-.25f,-.25f,1.25f,1.25f)){

//	Listen("/Devices/Input/Dialogic");
	SetClearState(false);

	#ifdef NEWSCALE

	parent->Apply(this);
	players  = new DynamicArray();
	channels = new DynamicArray();
	int dir = 0;
	int x = 1;
	int y = 1;
	int xr = 2;
	int yb = 2;
	int xl = 0;
	int yt = 0;
	int n = 1;
	for(int _x=0; _x<4; _x++){
		for(int _y=0; _y<4; _y++){
			Player *pl = new Player(h,Rect((float(x)/4.0f),(float(y)/4.0f),(float(x+1)/4.0f),(float(y+1)/4.0f)),st,n++);
			Apply(pl);
			players->Add(pl);
			channels->Add(0);
			switch(dir){
			case 0: if(++x==xr){ dir++; xr++; } break;
			case 1: if(++y==yb){ dir++; yb++; } break;
			case 2: if(--x==xl){ dir++; xl--; } break;
			case 3: if(--y==yt){ dir=0; yt--; } break;
			}
		}
	}

	#else

	parent->Apply(this);
	players  = new DynamicArray();
	channels = new DynamicArray();
	int dir = 0;
	int x = 1;
	int y = 1;
	int xr = 2;
	int yb = 2;
	int xl = 1;
	int yt = 1;
	int n = 1;
	for(int _x=0; _x<4; _x++){
		for(int _y=0; _y<4; _y++){
			Player *pl = new Player(h,Rect((float(x)/4.0f),(float(y)/4.0f),(float(x+1)/4.0f),(float(y+1)/4.0f)),st,n++);
			Apply(pl);
			players->Add(pl);
			channels->Add(0);
			switch(dir){
			case 0: if(++x==xr){ dir++; xr++; } break;
			case 1: if(++y==yb){ dir++; yb++; } break;
			case 2: if(--x==xl){ dir++; xl--; } break;
			case 3: if(--y==yt){ dir=0; yt--; x--; y--; } break;
			}
		}
	}
	#endif
	foo = 0;
	player_count=0;

	zoom = .5f;
	xz = yz = 0;

	Listen("/Devices/Input/Dialogic");
}
Exemple #13
0
void ServerThread::Resume() {
#ifdef _WIN32
    threadHandle = (HANDLE)_beginthreadex(NULL, 0, ExecuteServerThread, this, 0, &threadId);
    if(threadHandle == 0) {
#else
    int iRet = pthread_create(&threadId, NULL, ExecuteServerThread, this);
    if(iRet != 0) {
#endif
		AppendDebugLog("%s - [ERR] Failed to create new ServerThread\n", 0);
    }
}
//---------------------------------------------------------------------------

void ServerThread::Run() {
    bActive = true;
#ifdef _WIN32
    SOCKET s;
#else
	int s;
#endif
    sockaddr_storage addr;
	socklen_t len = sizeof(addr);

#ifndef _WIN32
    struct timespec sleeptime;
    sleeptime.tv_sec = 0;
    sleeptime.tv_nsec = 1000000;
#endif

	while(bTerminated == false) {
		s = accept(server, (struct sockaddr *)&addr, &len);

		if(iSuspendTime == 0) {
			if(bTerminated == true) {
#ifdef _WIN32
				if(s != INVALID_SOCKET)
					shutdown(s, SD_SEND);
                        
				closesocket(s);
#else
                if(s != -1)
                    shutdown(s, SHUT_RDWR);
                        
				close(s);
#endif
				continue;
			}

#ifdef _WIN32
			if(s == INVALID_SOCKET) {
				if(WSAEWOULDBLOCK != WSAGetLastError()) {
#else
            if(s == -1) {
                if(errno != EWOULDBLOCK) {
                    if(errno == EMFILE) { // max opened file descriptors limit reached
                        sleep(1); // longer sleep give us better chance to have free file descriptor available on next accept call
                    } else {
#endif
						clsEventQueue::mPtr->AddThread(clsEventQueue::EVENT_SRVTHREAD_MSG, 
                            ("[ERR] accept() for port "+string(ui16Port)+" has returned error.").c_str());
                    }
#ifndef _WIN32
				}
#endif
			} else {
				if(isFlooder(s, addr) == true) {
#ifdef _WIN32
					shutdown(s, SD_SEND);
					closesocket(s);
#else
                    shutdown(s, SHUT_RDWR);
                    close(s);
#endif
				}

#ifdef _WIN32
				::Sleep(1);
#else
                nanosleep(&sleeptime, NULL);
#endif
			}
		} else {
			uint32_t iSec = 0;
			while(bTerminated == false) {
				if(iSuspendTime > iSec) {
#ifdef _WIN32
					::Sleep(1000);
#else
					sleep(1);
#endif
					if(bSuspended == false) {
						iSec++;
					}
					continue;
				}

#ifdef _WIN32
				EnterCriticalSection(&csServerThread);
#else
				pthread_mutex_lock(&mtxServerThread);
#endif
				iSuspendTime = 0;
#ifdef _WIN32
				LeaveCriticalSection(&csServerThread);
#else
				pthread_mutex_unlock(&mtxServerThread);
#endif

				if(Listen(true) == true) {
					clsEventQueue::mPtr->AddThread(clsEventQueue::EVENT_SRVTHREAD_MSG, 
						("[SYS] Server socket for port "+string(ui16Port)+" sucessfully recovered from suspend state.").c_str());
				} else {
					Close();
				}
				break;
			}
		}
	}

    bActive = false;
}
//---------------------------------------------------------------------------

void ServerThread::Close() {
    bTerminated = true;
#ifdef _WIN32
	closesocket(server);
#else
    shutdown(server, SHUT_RDWR);
	close(server);
#endif
}
//---------------------------------------------------------------------------

void ServerThread::WaitFor() {
#ifdef _WIN32
    WaitForSingleObject(threadHandle, INFINITE);
#else
	if(threadId != 0) {
		pthread_join(threadId, NULL);
        threadId = 0;
	}
#endif
}
int main(void)
{
	unsigned int sockaddr;
	unsigned char mysocket;
	unsigned int rsize;

	/* Initialize the UART for ATmega168 96008N1    */
	uart_init();

	stdout = &uart_stdout;	//Required for printf init

	mysocket = 0;		// magic number! declare the socket number we will us
	sockaddr = W5100_SKT_BASE(mysocket);	// calc address of W5100 register set for this socket

	puts("AVR Ethernet\r\n");
/*
 *  Initialize the ATmega168 SPI subsystem
 */
	CS_PORT |= (1 << CS_BIT);	// pull CS pin high
	CS_DDR |= (1 << CS_BIT);	// now make it an output

	SPI_PORT = SPI_PORT | (1 << PORTB2);	// make sure SS is high
	SPI_DDR = (1 << PORTB3) | (1 << PORTB5) | (1 << PORTB2);	// set MOSI, SCK and SS as output, others as input
	SPCR = (1 << SPE) | (1 << MSTR);	// enable SPI, master mode 0
	SPSR |= (1 << SPI2X);	// set the clock rate fck/2

/*
 *  Load up the callback block, then initialize the Wiznet W5100
 */
	my_callbacks._select = &my_select;	// callback for selecting the W5100
	my_callbacks._xchg = &my_xchg;	// callback for exchanging data
	my_callbacks._deselect = &my_deselect;	// callback for deselecting the W5100
	my_callbacks._reset = &my_reset;	// callback for hardware-reset of the W5100

	W51_register(&my_callbacks);	// register our target-specific W5100 routines with the W5100 library
	W51_init();		// now initialize the W5100

/*
 *  Configure the W5100 device to handle PING requests.
 *  This requires configuring the chip, not a specific socket.
 */
	W51_config(&my_cfg);	// config the W5100 (MAC, TCP address, subnet, etc

	puts("Debug: AVR Ethernet after W5100 config\r\n");

/*
 *  The main loop.  Control stays in this loop forever, processing any received packets
 *  and sending any requested data.
 */
	while (1) {
		switch (W51_read(sockaddr + W5100_SR_OFFSET))	// based on current status of socket...
		{
		case W5100_SKT_SR_CLOSED:	// if socket is closed...
			if (OpenSocket(mysocket, W5100_SKT_MR_TCP, HTTP_PORT) == mysocket)	// if successful opening a socket...
			{
				Listen(mysocket);
				_delay_ms(1);
			}
			break;

		case W5100_SKT_SR_ESTABLISHED:	// if socket connection is established...
			rsize = ReceivedSize(mysocket);	// find out how many bytes
			if (rsize > 0) {
				if (Receive(mysocket, buf, rsize) != W5100_OK)
					break;	// if we had problems, all done
/*
 *  Add code here to process the payload from the packet.
 *
 *  For now, we just ignore the payload and send a canned HTML page so the client at least
 *  knows we are alive.
 */
				strcpy_P((char *)buf,PSTR("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nPragma: no-cache\r\n\r\n"));
				strcat_P((char *)buf,PSTR("<html>\r\n<body>\r\n"));
				strcat_P((char *)buf,PSTR("<title>Title</title>\r\n"));
				strcat_P((char *)buf,PSTR("<p>Hello world</p>\r\n"));
				strcat_P((char *)buf,PSTR("</body>\r\n</html>\r\n"));
				if (Send(mysocket, buf, strlen((char *)buf)) == W5100_FAIL) break;	// just throw out the packet for now

				DisconnectSocket(mysocket);
			} else	// no data yet...
			{
				_delay_us(10);
			}
			break;

		case W5100_SKT_SR_FIN_WAIT:
		case W5100_SKT_SR_CLOSING:
		case W5100_SKT_SR_TIME_WAIT:
		case W5100_SKT_SR_CLOSE_WAIT:
		case W5100_SKT_SR_LAST_ACK:
			CloseSocket(mysocket);
			break;
		}
	}

	return 0;
}
Exemple #15
0
void BaseServer::StartWeb(int port)
{
	m_ServWebSock.sockfd = Listen(port);
	m_ServWebSock.portno = port;

	if(m_ServWebSock.sockfd > 0){
		FD_SET(m_ServWebSock.sockfd,&m_setWebSock);
		if(m_iWebMaxSock < m_ServWebSock.sockfd)
			m_iWebMaxSock = m_ServWebSock.sockfd;
		cout<<GetSystemTime()<<": Web交互端口 "<<dec<<port<<" 开启成功."<<endl;
	}
	else{
		cout<<GetSystemTime()<<": "<<port<<" 端口开启失败,程序退出."<<endl;
		exit(1);
	}

	int clnt_sock;
	struct sockaddr_in clnt_addr;
	socklen_t clnt_addr_size = sizeof(clnt_addr);
	memset(&clnt_addr,0,sizeof(clnt_addr));
	
	fd_set tempsets;
	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;
	int result = 0;
	size_t buflen = MAXPACKLEN;
	char buf[MAXPACKLEN] = {0};
	
	while(true)
	{
		FD_ZERO(&tempsets);
		tempsets = m_setWebSock;
		timeout.tv_sec = 5;
		timeout.tv_usec = 0;
		result = select(m_iWebMaxSock+1,&tempsets,NULL,NULL,&timeout);
		if(result > 0)
		{
			if(FD_ISSET(m_ServWebSock.sockfd,&tempsets))
			{
				clnt_sock = accept(m_ServWebSock.sockfd,(struct sockaddr*)&clnt_addr,&clnt_addr_size);
				if(clnt_sock != -1)
				{
					if(m_bIsConnWeb){
						FD_CLR(m_ClntWebSock.sockfd,&m_setWebSock);
						close(m_ClntWebSock.sockfd);
					}
					m_ClntWebSock.sockfd = clnt_sock;
					FD_SET(m_ClntWebSock.sockfd,&m_setWebSock);
					if(m_iWebMaxSock < m_ClntWebSock.sockfd)
						m_iWebMaxSock = m_ClntWebSock.sockfd;
					m_ClntWebSock.portno = m_ServWebSock.portno;
					memcpy(m_ClntWebSock.ipaddr,inet_ntoa(clnt_addr.sin_addr),16);
					m_bIsConnWeb = true;
#ifndef NO_DEBUG
					cout<<GetSystemTime()<<": Web Client Connected "<<m_ClntWebSock.ipaddr<<endl;
#endif
				}
			}
			if(m_bIsConnWeb)
			{
				if(FD_ISSET(m_ClntWebSock.sockfd,&tempsets))
				{
					while(true)
					{
						memset(buf,0,buflen);
						int len = recvn(m_ClntWebSock.sockfd,buf,buflen);
						
						if(len == 6)
						{
							if((buf[0]&0xFF) == 0xAA && (buf[1]&0xFF) == 0xAA)
							{
								/********************添加获取站点信息及截止时间功能***************************/
								g_logs.WriteLog("收到采集数据截止日期更新命令.");
								pthread_mutex_lock(&m_infoMutex);
								iTimeSpace = GetConfigureFromDatabase();
								if(iTimeSpace == -1)
								{
									char space[4] = {0};
#ifndef NO_DEBUG									
									cout<<"获取数据库截止日期配置失败,从本地读取"<<endl;
#endif
									g_logs.WriteLog("获取数据库截止日期配置失败,从本地读取.");
									GetConfigureString("TIMESPACE",space,4,"30");
									iTimeSpace = atoi(space);
								}
								pthread_mutex_unlock(&m_infoMutex);
								cout<<"超过此截止天数的数据不再接收:"<<dec<<iTimeSpace<<" 天"<<endl;
								g_logs.WriteLog("超过此截止天数的数据不再接收:%d",iTimeSpace);
								/***************************************************** */
							}
						}
						else if(len == 0)
						{
							FD_CLR(m_ClntWebSock.sockfd,&m_setWebSock);
							close(m_ClntWebSock.sockfd);
							cout<<GetSystemTime()<<": Web Client DisConnect "<<m_ClntWebSock.ipaddr<<endl;
							m_bIsConnWeb = false;
							break;
						}
						else if(len < 0)
						{
							break;
						}
					}
				}
			}
		}
		else if(result < 0)
		{
			cout<<GetSystemTime()<<": Web select() error!"<<endl;
		}
	}
}
Exemple #16
0
int main (void){
	char * req = NULL;
	char mess[BUFFSIZE];
	char * data = NULL;
	char file[MAX_FILE_SIZE];
	int sockNum = 0, recSock = 0;
	int i = 0;
	int rc=0, rcr = 0;
	int accepted = 0;
	int cs=0;
	int chunkiterator = 0;
	int offset= 0;
    struct sockaddr_in from;
    socklen_t fromlen;
	FILE * fp = NULL;
	int bytecounter = 0;

	while(1){

	req = NULL;
	for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
	data = NULL;
	for(i = 0; i < MAX_FILE_SIZE ; i++) file[i] = 0;
	sockNum = 0;
	recSock = 0;
	i = 0;
	rc=0;
	rcr = 0;
	accepted = 0;
	cs=0;
	chunkiterator = 0;
	offset= 0;
    fromlen = 0;
	fp = NULL;
	bytecounter = 0;

	//build the request string
	req = buildReq(NUMCHUNKS, DATAPORT, FILENAME);

	//report request
	printf("sent request for \"%s\" in %d chunks over port %d\n", FILENAME, NUMCHUNKS, DATAPORT);

	//initialize buffers



	//open socket
	sockNum = Open("localhost", 11708);
	if (DEBUG) fprintf(stderr, "Socket Open\n");

	//start listening for response
	recSock = Listen(DATAPORT);

	//send the request
	rc = send( sockNum , req , (strlen(&req[4])+ 4) , 0 ) ;
	printf( "Sent %d\n%s\n" , rc , req ) ;

	//clean up
	free(req);
	req = NULL;
	close(sockNum);
		
	//start loop for each connection
	for (chunkiterator = 0; chunkiterator < NUMCHUNKS; chunkiterator++){
		//initialize variables
		for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;
		accepted = 0;
		offset =0;

		//try to accept a connection
		while (!accepted){
		    if (DEBUG) fprintf(stderr, "trying to accept connection. accepted = %d\n", accepted);
			fromlen = sizeof(from);
			cs = accept( recSock , (struct sockaddr *)&from  , &fromlen );
	
		    if (DEBUG) fprintf(stderr, "cs = %d\n", cs);
	
			//if it failed, report it
			//if it succeeded, raise tthe flafg
		    if (cs == -1){
				perror("accept:");
		    }else{
				(accepted = 1);
			}
		}
	
		if (DEBUG) fprintf(stderr, "done accepting. cs = %d\n", cs);
	   
		do {
			//cleart buffer
			if (DEBUG) fprintf(stderr, "clearing buffer\n");
			for(i = 0; i < BUFFSIZE ; i++) mess[i] = 0;

			//read from the socket into the buffer
			rc = recv( cs , &mess , sizeof(mess) , 0 ) ;
			if (DEBUG) fprintf(stderr, "finished reading %d bytes from socket. offset is currently %d\n", rc, offset);		
			if (rc == -1)
			    perror("recv");
			//if something was in fact read
			if (rc){
				//print it out
				//if (DEBUG) fprintf(stderr, "recieved: [%s]\n", mess);

				//if this  is the start of the packet find the offset
				if (offset == 0){
					offset = ntohl(*((int*)mess));
					if(DEBUG) fprintf(stderr, "firstoffset = %d\n", offset);
					data = &mess[4];
					rcr = rc - 4;

				// otherwise deal with it as normal
				} else {
					data = mess;
					rcr = rc;
				}

				if (DEBUG) fprintf(stderr, "done calculating offset and data pointers\n");
				
				//copy the data character by character into the file buffer
				for(i = 0; i < rcr; i++){
					//if (DEBUG) fprintf(stderr, "112: writing \'%c\' from index %d in buffer to index %d in file\n", data[i], i, *offset+i);
					file[offset] = data[i];
					offset++;
					bytecounter++;
				}
				if (DEBUG) fprintf(stderr, "done copying data\n");
			}
		} while (rc);

		close(cs);
	}

	//fprintf(stderr, "Final File:\n%s\nEnd of File\n", file);

	fp = fopen(WRITENAME, "w+");

	fwrite(file, bytecounter, 1, fp);

	fclose(fp);
	
	printf("wrote %d bytes to the file\n", bytecounter);

	close(recSock);	

	usleep(5000000);
	

	}

	return 0;
}
Exemple #17
0
void BaseServer::StartTrans(int port)
{
	m_ServTransSock.sockfd = Listen(port);
	m_ServTransSock.portno = port;

	if(m_ServTransSock.sockfd > 0){
		FD_SET(m_ServTransSock.sockfd,&m_setTransSock);
		if(m_iTransMaxSock < m_ServTransSock.sockfd)
			m_iTransMaxSock = m_ServTransSock.sockfd;
		cout<<GetSystemTime()<<": 转发端口 "<<dec<<port<<" 开启成功."<<endl;
	}
	else{
		cout<<GetSystemTime()<<": "<<port<<" 端口开启失败,程序退出."<<endl;
		exit(1);
	}

	int clnt_sock;
	struct sockaddr_in clnt_addr;
	socklen_t clnt_addr_size = sizeof(clnt_addr);
	memset(&clnt_addr,0,sizeof(clnt_addr));
	
	fd_set tempsets;
	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;
	int result = 0;
	size_t buflen = MAXPACKLEN;
	char buf[MAXPACKLEN] = {0};
	
	while(true)
	{
		FD_ZERO(&tempsets);
		tempsets = m_setTransSock;
		result = select(m_iTransMaxSock+1,&tempsets,NULL,NULL,&timeout);
		if(result > 0)
		{
			if(FD_ISSET(m_ServTransSock.sockfd,&tempsets))
			{
				clnt_sock = accept(m_ServTransSock.sockfd,(struct sockaddr*)&clnt_addr,&clnt_addr_size);
				if(clnt_sock != -1)
				{
					pthread_mutex_lock(&m_mutxTransSock);
					if(m_bIsConn){
						FD_CLR(m_ClntTransSock.sockfd,&m_setTransSock);
						close(m_ClntTransSock.sockfd);
					}
					m_ClntTransSock.sockfd = clnt_sock;
					FD_SET(m_ClntTransSock.sockfd,&m_setTransSock);
					if(m_iTransMaxSock < m_ClntTransSock.sockfd)
						m_iTransMaxSock = m_ClntTransSock.sockfd;
					m_ClntTransSock.portno = m_ServTransSock.portno;
					memcpy(m_ClntTransSock.ipaddr,inet_ntoa(clnt_addr.sin_addr),16);
					m_bIsConn = true;
					m_threadpool.setTransInfo(m_ClntTransSock.sockfd,m_bIsConn);
					pthread_mutex_unlock(&m_mutxTransSock);
#ifndef NO_DEBUG
					cout<<GetSystemTime()<<": Trans Client Connected "<<m_ClntTransSock.ipaddr<<endl;
#endif
				}
			}
			if(m_bIsConn)
			{
				if(FD_ISSET(m_ClntTransSock.sockfd,&tempsets))
				{
					while(true)
					{
						pthread_mutex_lock(&m_mutxTransSock);	/*  */
						int len = recvn(m_ClntTransSock.sockfd,buf,buflen);
						memset(buf,0,buflen);
						if(len == 0)
						{
							FD_CLR(m_ClntTransSock.sockfd,&m_setTransSock);
							close(m_ClntTransSock.sockfd);
#ifndef NO_DEBUG
							cout<<GetSystemTime()<<": Trans Client DisConnect "<<m_ClntTransSock.ipaddr<<endl;
#endif
							m_bIsConn = false;
							m_threadpool.setTransInfo(0,m_bIsConn);
							break;
						}
						else if(len < 0)
						{
							break;
						}
					}
					pthread_mutex_unlock(&m_mutxTransSock);
				}
			}
		}
		else if(result < 0)
		{
#ifndef NO_DEBUG
			cout<<GetSystemTime()<<": Trans select() error!"<<endl;
#endif
		}
	}//end of while
}
Exemple #18
0
int main()
{
    int Listenfd,connfd;
    socklen_t clilen;
    struct sockaddr_in cliaddr, servaddr;
    int val,len;
    pthread_t recv_thread, send_thread,getinfo_thread; 
    int res;
  
    Listenfd = Socket(AF_INET,SOCK_STREAM,0);
    
    val = 1;
    len = sizeof(int);
    Setsockopt(Listenfd, SOL_SOCKET, SO_REUSEPORT,(void *)&val, len);

    memset(&servaddr,0,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port =  htons(SERV_PORT);
    
    Bind(Listenfd,(SA*)&servaddr,sizeof(servaddr));
    Listen(Listenfd,LISTENQ);
    

    for( ; ;){
    
        
        val = 1;
        len = sizeof(int);
        Setsockopt(Listenfd, SOL_SOCKET, SO_DEBUG,(void *)&val, len);
             
        //sleep(8);
        clilen = sizeof(cliaddr);
        connfd = Accept(Listenfd,(SA*)&cliaddr,&clilen);
        
        openflag=1;
        res = pthread_create(&getinfo_thread, NULL, get_info, (void *)(&connfd));  
        if (res != 0)  
        {  
            perror("Thread creation failed!");  
            exit(EXIT_FAILURE);  
        } 
                  
        res = pthread_create(&recv_thread, NULL, recv_function, (void *)(&connfd));  
        if (res != 0)  
        {  
            perror("Thread creation failed!");  
            exit(EXIT_FAILURE);  
        }  
        
        res = pthread_create(&send_thread, NULL, send_function, (void *)(&connfd));  
        if (res != 0)  
        {  
            perror("Thread creation failed!");  
            exit(EXIT_FAILURE);  
        }  


        
        //sleep(200);
        
        //printf("close\n");
        //交由系统回收关闭文件描述符
        //Close(connfd);
    }
    return 0;
}
Exemple #19
0
int main (int argc, char **argv) {
  int    listenfd, connfd, n;
  struct sockaddr_in servaddr, clientaddr;
  
  //char   buf[MAXDATASIZE];
  char   recvline[MAXLINE + 1];
  
  //time_t ticks;
  char   error[MAXLINE + 1];
  
  //para obter o endereço do socket
  socklen_t addrlen = sizeof(clientaddr);

  //valor temporario para o id dos processos filhos
  pid_t child_pid;

  if (argc != 3) { //caso o usuário não tenha fornecido um IP e a porta para conexão
    strcpy(error,"uso: ");
    strcat(error,argv[0]);
    strcat(error," <Porta> <listen Backlog value");
    perror(error);
    exit(1);
  }

  //Inicializa o socket
  listenfd = Socket(AF_INET, SOCK_STREAM, 0);
  //Preenche informacoes relativas ao socket do servidor
  Servaddr(&servaddr, argv[1]);
  //Associa socket com um ip e uma porta
  Bind(listenfd, &servaddr);
  //Diz para o socket ouvir conexoes
  Listen(listenfd, atoi(argv[2]));
  //Registra funcao de handler
  Signal(SIGCHLD, sig_child);
  
  //Prepara arquivo de log

  time_t now;
  char timeString[256];
  FILE *log;
  
  while (1){
    //Retarda a remoção dos sockets da fila de conexões completas
    sleep(10);
    //Aceita uma conexao e atribui a um socket
    if ((connfd = Accept(listenfd, &clientaddr, &addrlen)) < 0){
      if (errno = EINTR){
	continue;
      }
      else{
	err_sys("accept error");
      }
    }

    //Registra conexao
    
    time(&now);
    strftime (timeString, 256, "%Y-%m-%d %H:%M:%S", localtime(&now));

    log = fopen("log.txt","a");
    if (log == NULL){
      printf ("Failed to log entry.\n");
    }
    else{
      fprintf(log,"[%s] %s:%u conectou-se\n",
	      timeString,
	      inet_ntoa(clientaddr.sin_addr),
	      ntohs(clientaddr.sin_port));
    }
    fclose(log);


    // Cria subprocesso que lidara com essa conexao
    
    if ((child_pid = fork()) == 0) { //Processo filho
      //Fecha socket para ouvir novas conexoes
      close(listenfd);
      //Imprime o endereço do socket local
      getsockname(connfd,(struct sockaddr *)&servaddr, &addrlen);
      printf("Endereço local: %s:%u \n",inet_ntoa(servaddr.sin_addr), ntohs(servaddr.sin_port));
     
      //Imprime o endereço do socket remoto
      printf("Endereço do cliente: %s:%u \n",
	     inet_ntoa(clientaddr.sin_addr),
	     ntohs(clientaddr.sin_port));
      
      while(1) {
        //Executa comandos enviados pelo cliente
	n = read(connfd, recvline, MAXLINE);

	if (n == 0){
	  // socket disconnected
	  break;
	}

	if (strcmp(recvline,"bye\n") == 0){
	  break;
	}
	else {
	  char outputbuffer[MAXLINE + 1];

	  recvline[n] = 0;
	  
	  FILE* p = popen(recvline,"r");
	
	  if (p == NULL){
	    printf("Erro executando comando.\n Valor de retorno: %d\n",
		   pclose(p) / 256);
	  }
	  else{

	    sprintf(outputbuffer, "(%s:%u) %s",
		    inet_ntoa(clientaddr.sin_addr),
		    ntohs(clientaddr.sin_port),
		    recvline);

	    printf("%s",outputbuffer);
	    	    
	    while (fgets(outputbuffer,MAXLINE+1,p)){
	      //printf("%s",outputbuffer);
	      write(connfd, outputbuffer, strlen(outputbuffer));
	    }
	    pclose(p);
	  }
	}
      }

      
      // Registra desconexao

      time(&now);
      strftime (timeString, 256, "%Y-%m-%d %H:%M:%S", localtime(&now));

      
      log = fopen("log.txt","a");
      if (log == NULL){
	printf ("Falha no registro\n");
      }
      else{
	fprintf(log,"[%s] %s:%u desconectou-se\n",
		timeString,
		inet_ntoa(clientaddr.sin_addr),
		ntohs(clientaddr.sin_port));
      }
      fclose(log);


      
      
      //Fecha socket da conexao

      printf("Cliente %s:%u desconectou-se.\n",
	     inet_ntoa(clientaddr.sin_addr),
	     ntohs(clientaddr.sin_port));

     
      close(connfd);	
      return(0);
    }
    printf("Numero do processo filho: %d\n", child_pid);
    close(connfd);
  }
}
Exemple #20
0
CWebServerSocket::CWebServerSocket(CWebServer* pWebServer, int port)
	: m_pWebServer(pWebServer)
{
	Create(port);
	Listen();
}
void  socket_servers()
{
int ascolto, conn_fd; //qui vengono definiti i descrittori del socket per il serverd
struct sockaddr_in server, serverd;//qui vengono definite le strutture per assegnare una porta e un ip al socket
int i=0;
socklen_t len;//qui si definisce len come un tipo intero di alemno 32 bit
pid_t pid;//qui viene definito il descrittore del processo figlio
int pool[10];
int scelta=0;


ascolto = Socket(AF_INET, SOCK_STREAM, 0);//qui viene creato il socket, al suo interno troviamo 3 parametri(il dominio,il tipo di socket(nel nostro caso SOCK_STREAM è un canale bidirezionale e sequenziale),infine il protocollo che viene inizializzato a 0) 
server.sin_family= AF_INET;//qui con AF_INET definiamo che tipo di protocollo usare(IPV4)
server.sin_addr.s_addr = inet_addr("127.0.0.5");//qui impostiamo l'indirizzo del servers,convertendo tramite htonl un numero a 32 bit dal formato macchina a quello di rete
server.sin_port= htons(8888);//qui impostiamo la porta per le comunicazioni con questo server,htons converte un numero a 16bit dal formato macchina a quello di rete


Bind(ascolto, (struct sockaddr *) &server, sizeof(server));//qui tramite la Bind assegnamo un indirizzo al socket

Listen(ascolto, 10);//qui mettiamo in ascolto il server e definiamo quante connessioni pendenti ci posso essere al massimo
printf("IL SERVERS AVVIATO..\n");


while(1)//Nel momento che entriamo nel while il server si manterrà sempre in ascolto
{
len = sizeof(serverd);
conn_fd = Accept(ascolto, (struct sockaddr *)&serverd, &len);//La funzione accept permette al server di accettare connessioni in entrata 
char *ip = inet_ntoa(serverd.sin_addr);//qui otteniamo l'indirizzo del client che si è connesso
if (Fork() == 0)
{



close(ascolto);//qui si chiude il descrittore della listen 
printf("Ip del del client connesso:%s\n",ip);//qui conosciamo ip del nuovo client connesso al server



FullRead(conn_fd,(char *)&scelta, sizeof(scelta));


if(scelta==1){//tramite questo if verifichiamo  chi si è connesso al servers, nel caso si effettua una chiamata alla funzione docenti
docenti(conn_fd, serverd);
}


else if(scelta==2){//tramite questo if verifichiamo se il client che si è connesso è il clients, nel caso si effettua una chiamata alla funzione segreteria_studenti
segreteria_studenti(conn_fd, serverd);
}




}

else //qui siamo nel processo padre

close (conn_fd);//qui si chiude la connesione al ritorno del figlio

}

}
Exemple #22
0
int main(int argc, char argv**)
{
	socklen_t len;
	int n, listenfd, connfd, char_in, count = 0;
	struct sockaddr_in  servaddr, cliaddr;
	char buff[40], wbuff[MAXLINE], rbuff[MAXLINE], cmd[16], path1[64]=".", path[64], vers[16];

	FILE * hFile;

	if(argc != 2)
	{
		err_quit("usage: a.out <Port>");
	}

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.sin_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(atoi(argv[1]));

	Bind(listenfd, (SA*) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	for( ; ; )
	{
		len = sizeof(cliaddr);

		connfd  = Accept(listenfd, (SA*) &cliaddr, &len);
		printf("\nConnection from %s, port %d\n", Inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)) ntohs(cliaddr.sin_port));

		while((n = read(connfd, rbuff, MAXLINE)) > 0)
		{
			rbuff[n] = 0;

			if(fputs(rbuff, stdout) == 0)
			{
				err_sys("fputs error");
			}

			if(strstr(rbuff,"\r\n\r\n") > 0)
			{
				break;
			}
		}

		if(n < 0)
		{
			err_sys("read error");
		}

		sscanf(rbuff, "%s %s %s", cmd, path, vers);
		strcat(path1, path);
		if(strcmp(path1, "./") == 0)
		{
			strcpy(path1, "./index.html");
		}

		hFile = fopen(path1, "r");
		if(hFile == NULL)
		{
			hFIle = fopen("error.html", "r");
		}

		strcpy(wbuff,"");

		while((char_in = fgetc(hFile)) != EOF)
		{
			wbuff(count) = char_in;
			count++;
		}

		wbuff(count) = 0;

		Write(connfd, wbuff, strlen(wbuff));

		count = 0;
		fclose(hFile);
		strcpy(path1,".");

		Close(connfd);
	}
}
Exemple #23
0
	bool Listen(V4addr &host, int maxcon) {
		m_LA = host;
		return Listen(maxcon);
	}
Exemple #24
0
int main()
{
    int Listenfd,connfd;
    socklen_t clilen;
    struct sockaddr_in cliaddr, servaddr;
    int val,len,i=0,last_in = 0,last_out = 0;;
    struct tcp_info_user info;
    char writebuf[TRANSSIZE];
    
    Listenfd = Socket(AF_INET,SOCK_STREAM,0);

    memset(&servaddr,0,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port =  htons(SERV_PORT);
    
    Bind(Listenfd,(SA*)&servaddr,sizeof(servaddr));
    Listen(Listenfd,LISTENQ);

    for( ; ;){
    

             
        clilen = sizeof(cliaddr);
        connfd = Accept(Listenfd,(SA*)&cliaddr,&clilen);
        
        
        val = 1;
        len = sizeof(int);
        Setsockopt(connfd, SOL_TCP, TCP_CORK,(void *)&val, len);
        
        
        val = 1;
        len = sizeof(int);
        Setsockopt(connfd, SOL_SOCKET, SO_DEBUG,(void *)&val, len);
        
        snprintf(writebuf,TRANSSIZE,"world01");
        Write(connfd,writebuf,8);
        
        snprintf(writebuf,TRANSSIZE,"world02");
        Write(connfd,writebuf,8);
        
        sleep_ms(200);
        val = 1;
        len = sizeof(int);
        Setsockopt(connfd, SOL_TCP, TCP_NODELAY,(void *)&val, len);
        
        
        snprintf(writebuf,TRANSSIZE,"world03");
        Write(connfd,writebuf,8);
        
        snprintf(writebuf,TRANSSIZE,"world04");
        Write(connfd,writebuf,8);
        
        
        
        sleep_ms(200);
        snprintf(writebuf,TRANSSIZE,"world05");
        Write(connfd,writebuf,50);
        
        i = 0;
        while(i < 100*200)
        {
            len = sizeof(info);
            Getsockopt(connfd, SOL_TCP, TCP_INFO,(void *)&info, (socklen_t *)&len);
            if( (last_in != info.tcpi_segs_in) || (last_out != info.tcpi_segs_out) )
            {
                //sleep_ms(1);
                len = sizeof(info);
                Getsockopt(connfd, SOL_TCP, TCP_INFO,(void *)&info, (socklen_t *)&len);
                
                printftcpinfo(&info);

                printf("i=%d\n",i);
                
                
                last_in = info.tcpi_segs_in;
                last_out = info.tcpi_segs_out;
            }
         
            
            sleep_ms(1);
            i++;
        }       

        
        

        
        sleep(200);
        
        printf("close\n");
        Close(connfd);
    }
    return 0;
}
void main() {

    struct hw_ip_pair *hi_pair;
    char IP_str[20], cache_hw_addr[6];
    fd_set rset;
    int cache_ifindex, cache_hatype;
    struct hw_addr HWaddr;

    hi_pair = malloc(sizeof(struct hw_ip_pair));
    get_hw_ip_pair(hi_pair);

    printf("My IP :%s,\t HW addr", hi_pair->ip_addr);
    print_mac_to_string(hi_pair->hw_addr);
    printf("\n");

    int pf_pack_sockfd = create_pf_pack_socket();
    void* buffer = (void*)malloc(ETH_FRAME_LEN);

    int listen_sockfd, conn_sockfd, clilen, n;
    struct sockaddr_un servaddr, cliaddr;
    char sendline[MAXLINE], recvline[MAXLINE];
    struct sockaddr_in *destIP = malloc(sizeof(struct sockaddr_in));
    char ip_addr[20];
    struct arp_packet *arp_req = malloc(sizeof(struct arp_packet));
    struct arp_packet *arp_rep = malloc(sizeof(struct arp_packet));
    struct arp_packet *arp_recv = malloc(sizeof(struct arp_packet));
    struct sockaddr_ll socket_address; 
    int ll_len = sizeof(struct sockaddr_ll);
    int i=0;

    listen_sockfd = Socket(AF_LOCAL, SOCK_STREAM, 0);
    unlink(SUN_PATH_ARP);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sun_family = AF_LOCAL;
    strcpy(servaddr.sun_path, SUN_PATH_ARP);
    Bind(listen_sockfd, (SA *) &servaddr, sizeof(servaddr));
    Listen(listen_sockfd, LISTENQ);

    int lookup_flag=0;
    clilen = sizeof(struct sockaddr_un);
    while(1) {

        FD_ZERO(&rset);

        FD_SET(listen_sockfd, &rset);
        FD_SET(pf_pack_sockfd, &rset);
        FD_SET(conn_sockfd, &rset);
        int max;

        if(conn_sockfd != 0)
            max = max(max(listen_sockfd, conn_sockfd),pf_pack_sockfd);
        else	
            max = max(listen_sockfd,pf_pack_sockfd);
        int ret = select(max+1, &rset, NULL, NULL, NULL);

        if(FD_ISSET(listen_sockfd, &rset)) {
            conn_sockfd = Accept(listen_sockfd, (SA *) &cliaddr, &clilen);
            /*			n = read(conn_sockfd, destIP, sizeof(struct sockaddr_in));
                        Inet_ntop(AF_INET, &(destIP->sin_addr), ip_addr, 20);

            // Lookup for the <HW,IP> pair in the ARP cache
            lookup_arp_cache(ip_addr, cache_hw_addr, &cache_ifindex, &cache_hatype,&lookup_flag);


            if(lookup_flag == 0) {
            printf("Entry not found from cache\n");
            create_arp_request_packet(arp_req, ip_addr, hi_pair);
            send_arp_request(pf_pack_sockfd, arp_req, hi_pair, conn_sockfd);
            }
            else{
            printf("Entry found from cache\n");
            // Send from cache
            HWaddr.sll_ifindex = cache_ifindex;
            HWaddr.sll_hatype = cache_hatype;
            HWaddr.sll_halen = sizeof(cache_hatype);

            memcpy(HWaddr.mac_addr, cache_hw_addr,6); 

            print_mac_to_string(HWaddr.mac_addr);
            Write(conn_sockfd, (void *)&HWaddr, sizeof(HWaddr));
            close(conn_sockfd);

            }
            printf("Sent ARP request\n");
             */		}

        else if(ret!= -1 && FD_ISSET(conn_sockfd, &rset)) {
            n = read(conn_sockfd, destIP, sizeof(struct sockaddr_in));
            Inet_ntop(AF_INET, &(destIP->sin_addr), ip_addr, 20);

            // Lookup for the <HW,IP> pair in the ARP cache
            lookup_arp_cache(ip_addr, cache_hw_addr, &cache_ifindex, &cache_hatype,&lookup_flag);


            if(lookup_flag == 0) {
                create_arp_request_packet(arp_req, ip_addr, hi_pair);
                printf("send 1\n");
                send_arp_request(pf_pack_sockfd, arp_req, hi_pair, conn_sockfd);
            }   
            else{
                // Send from cache
                HWaddr.sll_ifindex = cache_ifindex;
                HWaddr.sll_hatype = cache_hatype;
                HWaddr.sll_halen = sizeof(cache_hatype);

                memcpy(HWaddr.mac_addr, cache_hw_addr,6);

                //				print_mac_to_string(HWaddr.mac_addr);
                Write(conn_sockfd, (void *)&HWaddr, sizeof(HWaddr));
                close(conn_sockfd);
                conn_sockfd = 0;
            }
        }

        else if(FD_ISSET(pf_pack_sockfd, &rset)) {

            Recvfrom(pf_pack_sockfd, buffer, ETH_FRAME_LEN, 0, (SA *)&socket_address, &ll_len);
            void *data = buffer + 14;
            arp_rep = (struct arp_packet *)data;
            if (arp_rep->id == ARP_ID){
                if(arp_rep->op == ARP_REQ) {
                    if(strcmp(arp_rep->dest_IP, hi_pair->ip_addr) == 0) {

                        printf("Printing Ethernet Header and ARP Request Packet Received\n");
                        print_ethernet_and_arp(arp_rep->src_mac, arp_rep->dest_mac, arp_rep);
                        add_to_arp_cache_list(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, socket_address.sll_hatype, conn_sockfd, 1);
                        //						print_arp_cache_list();
                        create_arp_reply_packet(arp_recv, arp_rep->src_IP, hi_pair, arp_rep->src_mac, arp_rep->id);
                        send_arp_reply(pf_pack_sockfd, arp_recv, hi_pair, socket_address.sll_ifindex);
                    }
                    else {
                        update_arp_cache(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, 0, conn_sockfd);
                    }
                    continue;
                }
                else if(arp_rep->op == ARP_REP) {
                    if(ret == -1) {
                        delete_from_arp_cache(arp_rep->src_IP);
                        //						print_arp_cache_list();
                        continue;
                    }

                    printf("Printing Ethernet Header and ARP Reply Packet Received\n");
                    print_ethernet_and_arp(arp_rep->src_mac, arp_rep->dest_mac, arp_rep);

                    update_arp_cache(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, 0, conn_sockfd);
                    //					print_arp_cache_list();
                    HWaddr.sll_ifindex = socket_address.sll_ifindex;
                    HWaddr.sll_hatype = socket_address.sll_hatype;
                    HWaddr.sll_halen = socket_address.sll_halen;

                    memcpy(HWaddr.mac_addr, arp_rep->src_mac,6); 

                    //					print_mac_to_string(HWaddr.mac_addr);
                    Write(conn_sockfd, (void *)&HWaddr, sizeof(HWaddr));
                    close(conn_sockfd);
                    conn_sockfd = 0;
                    update_arp_cache(arp_rep->src_IP, arp_rep->src_mac, socket_address.sll_ifindex, 0, -1);
                    //					print_arp_cache_list();
                }
            }

        }
    }
}
Exemple #26
0
//
// TentacleThink
//
void CTentacle :: Cycle( void )
{
	SetNextThink( 0.1 );

	// ALERT( at_console, "%s %d %d %d %f %f\n", STRING( pev->targetname ), pev->sequence, m_iGoalAnim, m_iDir, pev->framerate, pev->health );

	if (m_MonsterState == MONSTERSTATE_SCRIPT || m_IdealMonsterState == MONSTERSTATE_SCRIPT)
	{
		Vector angles = GetAbsAngles();
		angles.y = m_flInitialYaw;
		SetAbsAngles( angles );
		pev->ideal_yaw = m_flInitialYaw;	
		ClearConditions( IgnoreConditions() );
		MonsterThink( );
		m_iGoalAnim = TENTACLE_ANIM_Pit_Idle;
		return;
	}

	DispatchAnimEvents( );
	StudioFrameAdvance( );

	ChangeYaw( pev->yaw_speed );

	CSound *pSound;

	Listen( );

	// Listen will set this if there's something in my sound list
	if ( HasConditions( bits_COND_HEAR_SOUND ) )
		pSound = PBestSound();
	else
		pSound = NULL;

	if ( pSound )
	{
		Vector vecDir;
		if (gpGlobals->time - m_flPrevSoundTime < 0.5)
		{
			float dt = gpGlobals->time - m_flPrevSoundTime;
			vecDir = pSound->m_vecOrigin + (pSound->m_vecOrigin - m_vecPrevSound) / dt - GetAbsOrigin();
		}
		else
		{
			vecDir = pSound->m_vecOrigin - GetAbsOrigin();
		}
		m_flPrevSoundTime = gpGlobals->time;
		m_vecPrevSound = pSound->m_vecOrigin;

		m_flSoundYaw = UTIL_VecToYaw ( vecDir ) - m_flInitialYaw;
		m_iSoundLevel = Level( vecDir.z );

		if (m_flSoundYaw < -180)
			m_flSoundYaw += 360;
		if (m_flSoundYaw > 180)
			m_flSoundYaw -= 360;

		// ALERT( at_console, "sound %d %.0f\n", m_iSoundLevel, m_flSoundYaw );
		if (m_flSoundTime < gpGlobals->time)
		{
			// play "I hear new something" sound
			char *sound;	

			switch( RANDOM_LONG(0,1) )
			{
			case 0: sound = "tentacle/te_alert1.wav"; break;
			case 1: sound = "tentacle/te_alert2.wav"; break;
			}

			// UTIL_EmitAmbientSound(ENT(pev), GetAbsOrigin() + Vector( 0, 0, MyHeight()), sound, 1.0, ATTN_NORM, 0, 100);
		}
		m_flSoundTime = gpGlobals->time + RANDOM_FLOAT( 5.0, 10.0 );
	}

	// clip ideal_yaw
	float dy = m_flSoundYaw;
	switch( pev->sequence )
	{
	case TENTACLE_ANIM_Floor_Rear:
	case TENTACLE_ANIM_Floor_Rear_Idle:
	case TENTACLE_ANIM_Lev1_Rear:
	case TENTACLE_ANIM_Lev1_Rear_Idle:
	case TENTACLE_ANIM_Lev2_Rear:
	case TENTACLE_ANIM_Lev2_Rear_Idle:
	case TENTACLE_ANIM_Lev3_Rear:
	case TENTACLE_ANIM_Lev3_Rear_Idle:
		if (dy < 0 && dy > -m_flMaxYaw)
			dy = -m_flMaxYaw;
		if (dy > 0 && dy < m_flMaxYaw)
			dy = m_flMaxYaw;
		break;
	default:
		if (dy < -m_flMaxYaw)
			dy = -m_flMaxYaw;
		if (dy > m_flMaxYaw)
			dy = m_flMaxYaw;
	}
	pev->ideal_yaw = m_flInitialYaw + dy;

	if (m_fSequenceFinished)
	{
		// ALERT( at_console, "%s done %d %d\n", STRING( pev->targetname ), pev->sequence, m_iGoalAnim );
		if (pev->health <= 1)
		{
			m_iGoalAnim = TENTACLE_ANIM_Pit_Idle;
			if (pev->sequence == TENTACLE_ANIM_Pit_Idle)
			{
				pev->health = 75;
			}
		}
		else if ( m_flSoundTime > gpGlobals->time )
		{
			if (m_flSoundYaw >= -(m_flMaxYaw + 30) && m_flSoundYaw <= (m_flMaxYaw + 30))
			{
				// strike
				m_iGoalAnim = LookupActivity( ACT_T_STRIKE + m_iSoundLevel );
			}
			else if (m_flSoundYaw >= -m_flMaxYaw * 2 && m_flSoundYaw <= m_flMaxYaw * 2) 
			{
				// tap
				m_iGoalAnim = LookupActivity( ACT_T_TAP + m_iSoundLevel );
			}
			else
			{
				// go into rear idle
				m_iGoalAnim = LookupActivity( ACT_T_REARIDLE + m_iSoundLevel );
			}
		}
		else if (pev->sequence == TENTACLE_ANIM_Pit_Idle)
		{
			// stay in pit until hear noise
			m_iGoalAnim = TENTACLE_ANIM_Pit_Idle;
		}
		else if (pev->sequence == m_iGoalAnim)
		{
			if (MyLevel() >= 0 && gpGlobals->time < m_flSoundTime)
			{
				if (RANDOM_LONG(0,9) < m_flSoundTime - gpGlobals->time)
				{
					// continue stike
					m_iGoalAnim = LookupActivity( ACT_T_STRIKE + m_iSoundLevel );
				}
				else
				{
					// tap
					m_iGoalAnim = LookupActivity( ACT_T_TAP + m_iSoundLevel );
				}
			}
			else if (MyLevel( ) < 0)
			{
				m_iGoalAnim = LookupActivity( ACT_T_IDLE + 0 );
			}
			else
			{
				if (m_flNextSong < gpGlobals->time)
				{
					// play "I hear new something" sound
					char *sound;	

					switch( RANDOM_LONG(0,1) )
					{
					case 0: sound = "tentacle/te_sing1.wav"; break;
					case 1: sound = "tentacle/te_sing2.wav"; break;
					}

					EMIT_SOUND(ENT(pev), CHAN_VOICE, sound, 1.0, ATTN_NORM);

					m_flNextSong = gpGlobals->time + RANDOM_FLOAT( 10, 20 );
				}

				if (RANDOM_LONG(0,15) == 0)
				{
					// idle on new level
					m_iGoalAnim = LookupActivity( ACT_T_IDLE + RANDOM_LONG(0,3) );
				}
				else if (RANDOM_LONG(0,3)  == 0)
				{
					// tap
					m_iGoalAnim = LookupActivity( ACT_T_TAP + MyLevel( ) );
				}
				else
				{
					// idle
					m_iGoalAnim = LookupActivity( ACT_T_IDLE + MyLevel( ) );
				}
			}
			if (m_flSoundYaw < 0)
				m_flSoundYaw += RANDOM_FLOAT( 2, 8 );
			else
				m_flSoundYaw -= RANDOM_FLOAT( 2, 8 );
		}

		pev->sequence = FindTransition( pev->sequence, m_iGoalAnim, &m_iDir );

		if (m_iDir > 0)
		{
			pev->frame = 0;
		}
		else
		{
			m_iDir = -1; // just to safe
			pev->frame = 255;
		}
		ResetSequenceInfo( );

		m_flFramerateAdj = RANDOM_FLOAT( -0.2, 0.2 );
		pev->framerate = m_iDir * 1.0 + m_flFramerateAdj;

		switch( pev->sequence)
		{
		case TENTACLE_ANIM_Floor_Tap:
		case TENTACLE_ANIM_Lev1_Tap:
		case TENTACLE_ANIM_Lev2_Tap:
		case TENTACLE_ANIM_Lev3_Tap:
			{
				Vector vecSrc;
				UTIL_MakeVectors( GetAbsAngles() );

				TraceResult tr1, tr2;

				vecSrc = GetAbsOrigin() + Vector( 0, 0, MyHeight() - 4);
				UTIL_TraceLine( vecSrc, vecSrc + gpGlobals->v_forward * 512, ignore_monsters, ENT( pev ), &tr1 );

				vecSrc = GetAbsOrigin() + Vector( 0, 0, MyHeight() + 8);
				UTIL_TraceLine( vecSrc, vecSrc + gpGlobals->v_forward * 512, ignore_monsters, ENT( pev ), &tr2 );

				// ALERT( at_console, "%f %f\n", tr1.flFraction * 512, tr2.flFraction * 512 );

				m_flTapRadius = SetBlending( 0, RANDOM_FLOAT( tr1.flFraction * 512, tr2.flFraction * 512 ) );
			}
			break;
		default:
			m_flTapRadius = 336; // 400 - 64
			break;
		}
		pev->view_ofs.z = MyHeight( );
		// ALERT( at_console, "seq %d\n", pev->sequence );
	}

	if (m_flPrevSoundTime + 2.0 > gpGlobals->time)
	{
		// 1.5 normal speed if hears sounds
		pev->framerate = m_iDir * 1.5 + m_flFramerateAdj;
	}
	else if (m_flPrevSoundTime + 5.0 > gpGlobals->time)
	{
		// slowdown to normal
		pev->framerate = m_iDir + m_iDir * (5 - (gpGlobals->time - m_flPrevSoundTime)) / 2 + m_flFramerateAdj;
	}
}
Exemple #27
0
int
main(int argc, char **argv)
{
	int					i, maxi, maxfd, listenfd, connfd, sockfd;
	int					nready, client[FD_SETSIZE];
	ssize_t				n;
	fd_set				rset, allset;
	char				line[MAXLINE];
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(7);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	maxfd = listenfd;			/* initialize */
	maxi = -1;					/* index into client[] array */
	for (i = 0; i < FD_SETSIZE; i++)
		client[i] = -1;			/* -1 indicates available entry */
	FD_ZERO(&allset);
	FD_SET(listenfd, &allset);

	for ( ; ; ) {
		rset = allset;
		nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(listenfd, &rset)) {	/* new client connection */
			printf("listening socket readable\n");
			sleep(5);
			clilen = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
#ifdef	NOTDEF
			printf("new client: %s, port %d\n",
					Inet_ntop(AF_INET, &cliaddr.sin_addr, 4, NULL),
					ntohs(cliaddr.sin_port));
#endif

			for (i = 0; i < FD_SETSIZE; i++)
				if (client[i] < 0) {
					client[i] = connfd;	/* save descriptor */
					break;
				}
			if (i == FD_SETSIZE)
				err_quit("too many clients");

			FD_SET(connfd, &allset);	/* add new descriptor to set */
			if (connfd > maxfd)
				maxfd = connfd;			/* for select */
			if (i > maxi)
				maxi = i;				/* max index in client[] array */

			if (--nready <= 0)
				continue;				/* no more readable descriptors */
		}

		for (i = 0; i <= maxi; i++) {	/* check all clients for data */
			if ( (sockfd = client[i]) < 0)
				continue;
			if (FD_ISSET(sockfd, &rset)) {
				if ( (n = Readline(sockfd, line, MAXLINE)) == 0) {
						 /* connection closed by client */
					Close(sockfd);
					FD_CLR(sockfd, &allset);
					client[i] = -1;
				}
				Writen(sockfd, line, n);

				if (--nready <= 0)
					break;				/* no more readable descriptors */
			}
		}
	}
}
Exemple #28
0
void BaseServer::StartListen(int minport,int maxport)
{
	m_iServCount = maxport-minport+1;
	if(m_iServCount > SERV_COUNT)
	{
		cout<<GetSystemTime()<<": 要求开启端口数超过限制,程序退出."<<endl;
		exit(1);
	}
	m_ServSocks = new ServInfo[m_iServCount];

	for(int i = minport;i <= maxport;i++)
	{
		m_ServSocks[i-minport].sockfd = Listen(i);	//套接字
		m_ServSocks[i-minport].portno = i;			//端口号
		FD_SET(m_ServSocks[i-minport].sockfd,&m_setServSock);
		if(m_ServSocks[i-minport].sockfd > 0)
		{
			if(m_ServSocks[i-minport].sockfd > m_iServMaxSock){
				m_iServMaxSock = m_ServSocks[i-minport].sockfd;
			}
			cout<<GetSystemTime()<<": "<<dec<<i<<" 端口开启成功."<<endl;
		}
		else
		{
			cout<<GetSystemTime()<<": "<<dec<<i<<" 端口开启失败,程序退出."<<endl;
			exit(1);
		}
	}
	cout<<GetSystemTime()<<": 全部端口开启完毕."<<endl;

	struct sockaddr_in clnt_addr;
	socklen_t clnt_addr_size = sizeof(clnt_addr);
	fd_set connfds;
	FD_ZERO(&connfds);
	int result = 0;
	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;

	while(true)
	{
		memset(&clnt_addr,0,clnt_addr_size);
		connfds = m_setServSock;
		result = select(m_iServMaxSock+1,&connfds,NULL,NULL,&timeout);
		if(result > 0)
		{
			for(int j = 0;j < m_iServCount;j++)
			{
				if(FD_ISSET(m_ServSocks[j].sockfd,&connfds))
				{
					if(m_iClntCount < MAX_CLIENT)
					{
CONNECT:
						int clnt_sock;
						clnt_sock = accept(m_ServSocks[j].sockfd,(struct sockaddr*)&clnt_addr,&clnt_addr_size);
						if(clnt_sock > 0)
						{
							pthread_mutex_lock(&m_mutxSock);
							m_ClntSocks[m_iClntCount].sockfd = clnt_sock;
							m_ClntSocks[m_iClntCount].portno = m_ServSocks[j].portno;
							m_ClntSocks[m_iClntCount].lasttime = time(NULL);
							memcpy(m_ClntSocks[m_iClntCount].ipaddr,inet_ntoa(clnt_addr.sin_addr),16);
							m_iClntCount++;

							if(m_iClntMaxSock < clnt_sock)
								m_iClntMaxSock = clnt_sock;
							FD_SET(clnt_sock,&m_setClntSock);
#ifndef NO_DEBUG
							cout<<GetSystemTime()<<": Client "<<inet_ntoa(clnt_addr.sin_addr)<<" Connected on port "<<dec<<m_ClntSocks[m_iClntCount-1].portno<<endl;
#endif
							pthread_mutex_unlock(&m_mutxSock);
						}
					}
					else
					{
						pthread_mutex_lock(&m_mutxSock);
						for(int k = m_iClntCount-1;k >= 0;k--)
						{
							close(m_ClntSocks[k].sockfd);
						}
						FD_ZERO(&m_setClntSock);
						m_iClntCount = 0;
						pthread_mutex_unlock(&m_mutxSock);
						cout<<GetSystemTime()<<": Sockets are over the max sock of allowed("<<dec<<MAX_CLIENT<<") Disconnect all connections."<<endl;
						goto CONNECT;
					}
				}
			}
		}
		else if(result < 0)
		{
#ifndef NO_DEBUG
			cout<<GetSystemTime()<<": select() 发生错误!"<<endl;
#endif
		}
	}// while(true)
}
Exemple #29
0
int
main(int argc, char **argv)
{
  int i, maxi, maxfd, listenfd, connfd, sockfd;
  int nready, client[FD_SETSIZE];
  ssize_t n;
  fd_set rset, allset;
  char buf[MAXLINE];
  socklen_t clilen;
  struct sockaddr_in cliaddr, servaddr;

  listenfd = Socket(AF_INET, SOCK_STREAM, 0);

  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);

  Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

  Listen(listenfd, LISTENQ);

  maxfd = listenfd;
  maxi = -1;
  for( i = 0; i < FD_SETSIZE; ++i)
    client[i] = -1;
  FD_ZERO(&allset);
  FD_SET(listenfd, &allset);

  for ( ; ; ) {
    rset = allset;
    nready = Select(maxfd+1, &rset, NULL, NULL, NULL);

    if (FD_ISSET(listenfd, &rset)) {
      clilen = sizeof(cliaddr);
      connfd = Accept(listenfd, (SA *)&cliaddr, &clilen);

      /* Put the new client into the clients array. */
      for (i = 0; i< FD_SETSIZE; i++)
	if(client[i] < 0) {
	  client[i] = connfd;
	  break;
	}
      if (i == FD_SETSIZE)
	err_quit("too many clients");
      FD_SET(connfd, &allset);
      if(connfd > maxfd)
	maxfd = connfd;		/* For select */
      if(i > maxi)
	maxi = i; 		/* max index in client[] array */

      if (--nready <= 0)
	continue;
    }

    for (i = 0; i<= maxi; i++) {
      if ( (sockfd = client[i]) < 0)
	continue;
      if (FD_ISSET(sockfd, &rset)) {
	if ( (n = Read(sockfd, buf, MAXLINE)) == 0) {
	  Close(sockfd);
	  FD_CLR(sockfd, &allset);
	  client[i] = -1;
	} else
	  Writen(sockfd, buf, n);

	if(--nready <= 0)
	  break;
      }
    }
  }
}
Exemple #30
0
int main(int argc, char **argv)
{
	int 	listenfd, connfd, udpfd, nready, maxfd1;
	char 	mesg[MAXLINE];
	pid_t  	childpid;
	fd_set	rset;
	ssize_t	n;
	socklen_t	len;
	const	int	on = 1;
	struct sockaddr_in 	servaddr, cliaddr;


	void sig_chld(int);

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	Setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	Bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	udpfd = Socket(AF_INET, SOCK_DGRAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	Bind(udpfd, (SA *)&servaddr, sizeof(servaddr));

	Signal(SIGCHLD, sig_chld);

	FD_ZERO(&rset);

	maxfd1 = max(listenfd, udpfd) + 1;

	for(;;)
	{
		FD_SET(listenfd, &rset);
		FD_SET(udpfd, &rset);

		if( (nready = select(maxfd1, &rset, NULL, NULL, NULL)) < 0)
		{
			if( errno == EINTR)
				continue;
			else
			{
				printf("select error.");
				exit(1);
			}
		}

		if( FD_ISSET(listenfd, &rset) )
		{
			len = sizeof(cliaddr);
			connfd = Accept(listenfd, (SA *)&cliaddr, &len);

			if( (childpid = fork()) == 0)
			{
				/* child process */
				Close(listenfd);
				str_echo(connfd);
				exit(0);
			}
			Close(connfd);
		}

		if( FD_ISSET(udpfd, &rset))
		{
			len = sizeof(cliaddr);
			n = Recvfrom(udpfd, mesg, MAXLINE, 0, (SA *)&cliaddr, &len);

			Sendto(udpfd, mesg, n, 0, (SA *)&cliaddr, len);
		}
	}

	exit(0);
}