コード例 #1
0
void Client(char *filename)
{
    int clientSocketDescriptor;
    int connectResult;
    FILE *rdfile;

    rdfile = fopen(filename, "r");
    if (rdfile == NULL)
    {
        puts ("Error while opening file.");
        return;
    }
    clientSocketDescriptor = StartClient("tcp");
    connectResult = ClientConnect(clientSocketDescriptor, "127.0.0.1", 6660);
    if (connectResult == -1)
    {
        return;
    }
    if (SendFileName(clientSocketDescriptor, filename) == -1)
    {
        return;
    }
    if (SendFileSize(clientSocketDescriptor, rdfile) == -1)
    {
        return;
    }
    ClientProcess(clientSocketDescriptor, rdfile);
    ShutdownSocket(clientSocketDescriptor);
    CloseSocket(clientSocketDescriptor);
    fclose(rdfile);

    return;
}
コード例 #2
0
ファイル: TCPClient.cpp プロジェクト: kleberandrade/dream-net
/**
* Abre conexão com o servidor
* @return conexão estabelecida true), caso contrário (false)
*/
bool TCPClient::Open(void)
{
	/// Cria um socket para conexão com o servidor
	m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (m_Socket == INVALID_SOCKET) 
	{
		printf("Socket failed with error: %ld\n", WSAGetLastError());
		ShutdownSocket();
		return false;
	}

	/// configura as informações do enderço
	sockaddr_in client_service;
	client_service.sin_family = AF_INET;
	client_service.sin_port = htons(m_iPort);
	client_service.sin_addr.s_addr = inet_addr(m_sAddress);
	
	/// Conecta no servidor
	m_iResult = connect(m_Socket, (sockaddr*)&client_service, sizeof(client_service));
	if (m_iResult == SOCKET_ERROR) 
	{
		printf("The server is down... did not connect.\r\n");
		Close();
		return false;
	}
	
	// se a conexão falahar
	if (m_Socket == INVALID_SOCKET)
	{
		printf("Unable to connect to server!\r\n");
		ShutdownSocket();
		return false;
	}

	// Desabilita o algoritmo Nagle
	setsockopt(m_Socket, IPPROTO_TCP, TCP_NODELAY, &m_cNagle, sizeof(m_cNagle));
	
	printf("Successfully connected.\r\n");
	return true;
}
コード例 #3
0
ファイル: TCPClient.cpp プロジェクト: kleberandrade/dream-net
/**
* Recebe um buffer (mensagem) do servidor
* @param buffer - buffer recebido do servidor
* @param bufferSize - tamanho do buffer recebido
* @return informações do recebimento do buffer
*/
int TCPClient::Receiver(char *buffer, int bufferSize)
{
	m_iResult = NetworkServices::ReceiveMessage(m_Socket, buffer, bufferSize);

	if (m_iResult == SOCKET_ERROR)
	{
		printf("Recv failed with error : %d\n", WSAGetLastError());
		Close();
		ShutdownSocket();
	}

	return m_iResult;
}
コード例 #4
0
ファイル: TCPClient.cpp プロジェクト: kleberandrade/dream-net
/**
* Envia uma mensagem para o servidor
* @param message - mensagem a ser enviada para o servidor
* @param messageSize - tamanho da mensagem a ser enviada
* @return informações do envio da mensagem
*/
int TCPClient::Send(char *message, int messageSize)
{
	m_iResult = NetworkServices::SendMessage(m_Socket, message, messageSize);
	
	if (m_iResult == SOCKET_ERROR)
	{
		printf("Send failed with error: %d\n", WSAGetLastError());
		Close();
		ShutdownSocket();
	}

	return m_iResult;
}
コード例 #5
0
ファイル: gzip.c プロジェクト: 2dot4/Psiphon3-for-Linux
static int Zfclose(FILE *fp){
	int fd;
	int sock;
	int rcode;

	fflush(fp);
	fd = fileno(fp);
	if( sock = SocketOf(fd) ){
		ShutdownSocket(fileno(fp));
	}
	rcode = fclose(fp);
	GZDBG(stderr,"-- %X Zfclose(%X)=%d %s\n",TID,fd,rcode,
		sock?"(SOCKET)":"");

	return rcode;
}
コード例 #6
0
void ServerProcessing(ConnectionInfo *connectionInfo)
{

    int receivedBytes;

    char buffer[1000];


        if (urgentData > 0)
        {
            printf("Received %d bytes.\n", connectionInfo->totalBytesRead);
            urgentData--;
            ReceiveOOBData(connectionInfo->socket);
        }
        receivedBytes = recv(connectionInfo->socket, buffer, 1000, 0);
        if (receivedBytes > 0)
        {
            fwrite(buffer, 1, receivedBytes, connectionInfo->wrfile);
            connectionInfo->totalBytesRead += receivedBytes;
        }
        else
        {
            if (errno != EINTR)
            {
                puts("Client connection has been closed.");
                if (connectionInfo->totalBytesRead < connectionInfo->fileSize)
                {
                    puts("FileSize mismatch.");
                }
            }
        }

    if (connectionInfo->totalBytesRead >= connectionInfo->fileSize)
    {
        printf ("File receive completed. Received %d bytes.", connectionInfo->totalBytesRead);
        fclose(connectionInfo->wrfile);
        ShutdownSocket(connectionInfo->socket);
        CloseSocket(connectionInfo->socket);
        puts("Client connection has been closed.");
        DeleteInfo(&info, connectionInfo->socket);
    }

    return;
}
コード例 #7
0
ファイル: TCPClient.cpp プロジェクト: kleberandrade/dream-net
/**
* Inicializa o WinSock
* @return inicialização realizada com sucesso (true), falha ao inicializar (false)
*/
bool TCPClient::InitializeSockets(void)
{
	WSADATA wsaData;
	// Using MAKEWORD macro, Winsock version request 2.2
	WORD wVersionRequested = MAKEWORD(2, 2);
	int wsaerr = WSAStartup(wVersionRequested, &wsaData);;

	if (wsaerr != 0)
	{
		/* Tell the user that we could not find a usable WinSock DLL.*/
		printf("The Winsock dll not found!\n");
		return false;
	}
	else
	{
		printf("The Winsock dll found!\n");
		printf("The status: %s.\n", wsaData.szSystemStatus);
	}

	/* Confirm that the WinSock DLL supports 2.2.*/
	/* Note that if the DLL supports versions greater    */
	/* than 2.2 in addition to 2.2, it will still return */
	/* 2.2 in wVersion since that is the version we      */
	/* requested.                                        */
	if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
	{
		/* Tell the user that we could not find a usable WinSock DLL.*/
		printf("The dll do not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
		ShutdownSocket();
		return false;
	}
	else
	{
		printf("The dll supports the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion), HIBYTE(wsaData.wVersion));
		printf("The highest version this dll can support: %u.%u\n", LOBYTE(wsaData.wHighVersion), HIBYTE(wsaData.wHighVersion));
	}

	return true;
}
コード例 #8
0
ファイル: process.c プロジェクト: 2dot4/Psiphon3-for-Linux
static int threadFilter(Connection *Conn,PCStr(fname),iFUNCP func,FILE *ioin,FILE *out,PCStr(args)){
	int code;
	IStr(buf,1);
	int osock;

	setthreadgid(0,STX_tid);
	osock = ClientSock;
	//ClientSock = dup(ClientSock);
	Verbose("-- F openFilter: %s [%d][%d] [%d]>>[%d]\n",
		fname, osock,ClientSock, FromS,ToC);
	// write(fileno(ioin),"\n",1); /* for sync. of thread_fork */
	PollIn(fileno(ioin),1000);

	clearConnPTR(Conn);
	code = (*func)(Conn,ioin,out,args);
	Verbose("-- F openFilter: DONE %d\n",code);
	fflush(out);
	ShutdownSocket(fileno(ioin));
	/*
	close(fth.f_sync[1]);
	*/
	sv1log("-- F openFilter: EXIT(%d) %s\n",code,fname);
	return 0;
}
コード例 #9
0
ファイル: client_core.cpp プロジェクト: iamyuiwong/socket
void * ClientRecevier::run(void * arg)
{
	if (NULL == arg) {
		return reinterpret_cast<void *>(-error::INVALIDSOCKARG);
	}
	SockClientRecviveParams * scr = (SockClientRecviveParams *)arg;
	/* Dump */
	int sockfd = scr->sockfd();
	ClientHandler * clientHandler = scr->clientHandler();
	SockDidFinish fb;
	fb.fd = sockfd;/* Fill FI sockfd */
	bool teminate = clientHandler->shouldTeminateRecv(sockfd);
	uint8_t * buf = new uint8_t[4096];
	SockRecved rcv;
	rcv.fd = sockfd;
	memcpy(&(rcv.info), scr->from(), sizeof(NetProtocol));
	int ret;
	while (0 == teminate) {
		memset(buf, 0, 4096);
		ret = RecvFromSockfd(
			sockfd, buf, 0, 4096, 15 * 1e6, 15 * 1e6);
		if ((ret < 0) && (ret > -1000)) {
			fb.code = ret;/* Fail */
			ShutdownSocket(sockfd, shutdownhow::RDWR);
			CloseSocket(sockfd);
			clientHandler->didFinish(fb);
			goto end;
		} else if (0 == ret) {
			/* disconnected */
			fb.code = 0;
			ShutdownSocket(sockfd, shutdownhow::RDWR);
			CloseSocket(sockfd);
			clientHandler->didFinish(fb);
			goto end;
		} else if (ret > 0) {
			/* success */
			rcv.data = buf;
			rcv.count = ret;
			clientHandler->didReceive(rcv);
		} else {
			/* < -1000 timeout */
		}
		teminate = clientHandler->shouldTeminateRecv(sockfd);
	}
	fb.code = 1;/* user terminate */
	ShutdownSocket(sockfd, shutdownhow::RDWR);
	CloseSocket(sockfd);
	clientHandler->didFinish(fb);
end:
	if (NULL != scr) {
		delete scr;
		scr = NULL;
	}
	if (NULL != buf) {
		delete[] buf;
		buf = NULL;
	}
	if (NULL != clientHandler) {
		if (NULL != clientHandler->gc()) {
			clientHandler->gc()->gc(clientHandler);
		}
		/* else has released */
		clientHandler = NULL;
	}

	return (void *)0;/* success */
}
コード例 #10
0
/****** C_Communication::DoComm() const ****************************************
*  NAME
*     C_Communication::DoComm() const -- does the communication
*
*  SYNOPSIS
*     int C_Communication::DoComm() const
*
*  FUNCTION
*     Does the communication with sge_shepherd. I.e. whenever a sge_shepherd
*     connects to the server, it receives the request, does what is requested
*     and then shuts down the connection.
*
*  RESULT
*     int - 0 if command was successfully received and processed, 1 else
*
*  NOTES
*******************************************************************************/
int C_Communication::DoComm() const
{
   int                ret = 1;
   int                idx = 0;
   SOCKET             comm_sock;
   int                remote_saddr_len;
   struct sockaddr_in remote_saddr;
   char               szMessage[1024];
   char               command[COMMAND_SIZE];
   const int          commandsize = sizeof(command);
   C_Job              Job;
   C_Job              *pJob = NULL;
   en_request_type    request_type;

   remote_saddr_len = sizeof(remote_saddr);
   comm_sock = accept(m_ListenSocket, 
                     (struct sockaddr*)&remote_saddr, &remote_saddr_len);
   if(comm_sock == INVALID_SOCKET) {
      return WSAGetLastError();
   }

   ZeroMemory(command, COMMAND_SIZE);
   while((ret=recv(comm_sock, command+idx, commandsize-idx, 0))>0) {
      idx += ret;
      if(command[idx-1] == EOF) {
         break;
      }
   }
   if(ret == -1) {
      ret = WSAGetLastError();
      ShutdownSocket(&comm_sock);
      return ret;
   }
   ret = 0;

   request_type = Job.ParseCommand(command);

   switch(request_type) {
      case req_job_start:
         POSITION Pos;
         HANDLE   hThread;

         if(g_bAcceptJobs) {
            Job.m_comm_sock = comm_sock;

            sprintf(szMessage, "Starting job %lu.%lu %s", 
               Job.m_job_id, Job.m_ja_task_id,
               Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
            WriteToLogFile(szMessage);

            // try to put job in job list
            pJob = new C_Job(Job);
            Pos = g_JobList.AddJobToList(pJob);
         }

         if(Pos != NULL) {
            // job is not already in job list, send ACK and start worker thread
            hThread = CreateThread(NULL, 0, JobStarterThread, 0, 0, 0);
            CloseHandle(hThread);
         } else {
            // job is already in job list, send NACK and delete job object
            strcpy(szMessage, "NAK");
            szMessage[strlen(szMessage)+1] = (char)EOF;
            send(comm_sock, szMessage, (int)strlen(szMessage)+2, 0);
            ShutdownSocket(&comm_sock);
            delete pJob;
            pJob = NULL;
         }
         break;

      case req_send_job_usage:
         pJob = g_JobList.RemoveJobFromList(Job);
         if(pJob) {
            pJob->m_comm_sock = comm_sock;
            SendJobUsage(*pJob);
            delete pJob;
            pJob = NULL;
            sprintf(szMessage, "Sending usage of job %lu.%lu %s",
                        Job.m_job_id, Job.m_ja_task_id,
                        Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
         } else {
            sprintf(szMessage, "Warning: Job %lu.%lu %s not found!",
                        Job.m_job_id, Job.m_ja_task_id,
                        Job.m_pe_task_id ? Job.m_pe_task_id : "<null>");
         }
         WriteToLogFile(szMessage);
         ShutdownSocket(&comm_sock);
         break;

      case req_forward_signal:
         // lock access to job list
         CSingleLock singleLock(&g_JobList.m_JobListMutex);
         singleLock.Lock();
         pJob = g_JobList.FindJobInList(Job);
         if(pJob
            && pJob->m_JobStatus != js_Finished
            && pJob->m_JobStatus != js_Failed
            && pJob->m_JobStatus != js_Deleted) {
            BOOL bRet = FALSE;
            char szAnswer[100];
            int  sent;

            if(pJob->m_hProcess != INVALID_HANDLE_VALUE
               && pJob->m_hJobObject != INVALID_HANDLE_VALUE) {
               bRet = TerminateJobObject(pJob->m_hJobObject, 0);
               if(bRet) {
                  pJob->m_JobStatus = js_Deleted;
               }
            }
            singleLock.Unlock();
            
            sprintf(szAnswer, "%s", bRet ? "ACK" : "NAK");
            szAnswer[strlen(szAnswer)+1] = (char)EOF;
            sent = send(comm_sock, szAnswer, (int)strlen(szAnswer)+2, 0);
            if(sent >= 0) {
               ret = 0;
            }
         } else {
            singleLock.Unlock();
         }
         ShutdownSocket(&comm_sock);
         break;
   }
   return ret;
}