void HandleTCPClient(int clntSocket) {
  char buffer[BUFSIZE]; // Buffer for echo string

  // Receive message from client
  ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
  if (numBytesRcvd < 0)
    DieWithSystemMessage("recv() failed");

  // Send received string and receive again until end of stream
  while (numBytesRcvd > 0) { // 0 indicates end of stream
    // Echo message back to client
    ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
    if (numBytesSent < 0)
      DieWithSystemMessage("send() failed");
    else if (numBytesSent != numBytesRcvd)
      DieWithUserMessage("send()", "sent unexpected number of bytes");

    // See if there is more data to receive
    numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
    if (numBytesRcvd < 0)
      DieWithSystemMessage("recv() failed");
  }

  close(clntSocket); // Close client socket
}
示例#2
0
int main(int argc, char *argv[])
{
    if(argc != 2)   // Test for corrent number of arguments
        DieWithUserMessage("Parameter(s)", "<Server Port>");

    in_port_t servPort = atoi(argv[1]);     // First arg: local port

    // Create socket for incoming connections
    int servSock = socket(AF_INET6, SOCK_STREAM, IPPORT_TCP);
    if(sockSock < 0)
        DieWithSystemMessage("socket() failed");

    // Construct local address structure
    struct sockaddr_int servAddr;   // Local address
    memset(&servAddr, 0, sizeof(servAddr));     // Zero out structure
    servAddr.sin6_family = AF_INET6;    // Zero out structure
    servAddr.sin6_addr = in6addr_any;   // IPv6 address family
    servAddr.sin6_port = htons(servPort); // Local port

    // Bind to the local address
    if(bind(servSock, (struct sockaddr *)&servAddr, sizeof(servAddr)) < 0)
        DieWithSystemMessage("bind() failed");

    // Mark the socket so ti will listen for incoming connections
    if(listen(servSock, MAXPENDING) < 0)
        DieWithSystemMessage("listen() failed");

    for(;;)     // Run forever
    {
        struct sockaddr_in6 clntAddr;   // Client address
        // Set length of client address structure (in-out parameter)
        socklen_t clntAddrLen = sizeof(clntAddr);

        // Wait for a client to connect
        int clntSock = accept(servSock, (struct sockaddr *)&clntAddr, &clntAddrLen);
        if(clntSock < 0)
            DieWithSystemMessage("accept() failed");

        // clntSock is connected to a client!

        char clntName[INET6_ADDRSTRLEN];    // Array to contain client address string
        if(inet_ntop(AF_INET6, &clntAddr.sin6_addr.s6_addr, clntName,
                sizeof(clntName)) != NULL)
            printf("Handing client %s/%d\n", clntName, ntohs(clntAddr.sin6_port));
        else
            puts("Unable to get client address");

        HandleTCPClient(clntSock);
    }
    // NOT REACHED
}
void HandleTCPClient(int clntSocket, char* clntName) {
	char buffer[BUFSIZE]; // Buffer for echo string

	// Receive message from client
	ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
	if (numBytesRcvd < 0) {
		DieWithSystemMessage("recv() failed");
	}
	buffer[numBytesRcvd] = '\0';
	printf("Number of bytes received: %d\n", (int)numBytesRcvd);

  	// Send received string and receive again until end of stream
	while (numBytesRcvd > 0) { // 0 indicates end of stream
		// Echo message back to client
		ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
		if (numBytesSent < 0)
			DieWithSystemMessage("send() failed");
		else if (numBytesSent != numBytesRcvd)
			DieWithUserMessage("send()", "sent unexpected number of bytes");
		
		// Give the message to Napster's parser
		char* filename = malloc((numBytesRcvd-1)*sizeof(char));
		printf("Received string: %s\n", buffer);
		memmove(filename, &buffer[1], numBytesRcvd-1);
		filename[numBytesRcvd-1] = '\0';

		switch (buffer[0] - '0')
		{
			case ADDFILE: addFile(filename, clntName);
					break;
			case DELETEFILE: printf("Status of delete: %d\n",deleteFile(filename, clntName));
					break;
			case LISTFILES: viewFiles(clntSocket);
					break;
		}

		free(filename);

		// See if there is more data to receive
		printf("Waiting for more data from client...\n");
		numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
		buffer[numBytesRcvd] = '\0';    // Terminate the string!
		if (numBytesRcvd < 0) {
			DieWithSystemMessage("recv() failed");
		}
		printf("Processing data recieved, \"%s\"...\n", buffer);
		printf("Number of bytes received (currently) : %d\n",(int)numBytesRcvd);
  	}

	close(clntSocket); // Close client socket
}
示例#4
0
int Connect(int socket, const sockaddr *foreignAddress, socklen_t addressLength){
	int n;
	n = connect(socket, foreignAddress, addressLength);
	if(n<0)
		DieWithSystemMessage("connect() failed");
	return n;
}
示例#5
0
int Close(int socket){
	int n;
	n = close(socket);
	if(n<0)
		DieWithSystemMessage("close() failed");
	return n;
}
示例#6
0
int Bind(int socket, sockaddr *localAddress, socklen_t addressSize){
	int n;
	n = bind(socket, localAddress, addressSize);
	if(n<0)
		DieWithSystemMessage("bind() failed");
	return n;
}
示例#7
0
ssize_t Recv(int socket, void *rcvBuffer, size_t bufferLength, int flags){
	ssize_t n;
	n = recv(socket, rcvBuffer, bufferLength, flags);
	if(n<0)
		DieWithSystemMessage("recv() failed");
	return n;
}
示例#8
0
void HandleTCPClient(int clntSocket, int client_id)
{
    char buffer[BUFSIZE]; // Buffer for echo string

    char logname[16];
    sprintf(logname, "log_file%03d.log", client_id);
    log_file = fopen(logname, "w"); //open log file

    numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0); // receive first frame

    while (numBytesRcvd > 0)
    {
        // Use this format to extract the frame content
        printf("%u", *(uint16_t *)buffer);
        printf("%c", buffer[2]);
        printf("%c", buffer[3]);
        printf("%s\n", buffer + 4);
        printf("%ld\n", numBytesRcvd);
        fflush(stdout);


        buffer[numBytesRcvd] = '\0';
        processInput(buffer, clntSocket, client_id);
        printf("process input returns\n\n\n\n");

        numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
        if (numBytesRcvd < 0)
            DieWithSystemMessage("recv() failed");
    }

    fclose(log_file);
}
示例#9
0
int main(int argc, char *argv[]) {

  if (argc != 3) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)",
        "<Server Address/Name> [<Server Port/Service>]");

  char *server = argv[1];     // First arg: server address/name
  char *service = argv[2]; 

  // Create a connected TCP socket
  int sock = SetupTCPClientSocket(server, service);
  if (sock < 0)
    DieWithUserMessage("SetupTCPClientSocket() failed", "unable to connect");

  FILE *str = fdopen(sock,"r+");
  char buffer[MAXSTRINGLENGTH];
  //while((scanf("%s",buffer) != EOF)){
  while(gets(buffer) && strlen(buffer) != 0){
      int sSize;
      int stringLen = strlen(buffer); // Determine input length
      if((sSize = PutMsg(buffer, stringLen, str)) < 0)
          DieWithSystemMessage("PutMsg() failed");
      //printf("Sending %d-byte..\n",sSize);
      /*
      GetNextMsg(str,buffer,MAXSTRINGLENGTH);
      printf("get echo\n");
      printf("%s\n",buffer);
      */
      memset(buffer,0,sizeof(buffer));
  }
  fclose(str);
  printf("quit.\n");
  return 0;
}
示例#10
0
int Open(const char *pathname, int oflag){
    int n=open(pathname, oflag);
    if(n == -1)
        DieWithSystemMessage("open() failed");
    else
        return n;
}
示例#11
0
int Socket(int domain, int type, int protocol){
	int sock;
	sock = socket(domain, type, protocol);
	if(sock<0)
		DieWithSystemMessage("socket() failed");
	return sock;
}
int main(int argc, char *argv[]) {

  if (argc != 2) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)", "<Server Port/Service>");

  char *servPort = argv[1]; // First arg:  local port
  int servSock = SetupTCPServerSocket(servPort);
  if (servSock < 0)
    DieWithUserMessage("SetupTCPServerSocket() failed", "unable to establish");
  for (;;) { // Run forever
    int clntSock = AcceptTCPConnection(servSock);

    // Create separate memory for client argument
    struct ThreadArgs *threadArgs = (struct ThreadArgs *) malloc(
        sizeof(struct ThreadArgs));
    if (threadArgs == NULL)
      DieWithSystemMessage("malloc() failed");
    threadArgs->clntSock = clntSock;

    // Create client thread
    pthread_t threadID;
    int returnValue = pthread_create(&threadID, NULL, ThreadMain, threadArgs);
    if (returnValue != 0)
      DieWithUserMessage("pthread_create() failed", strerror(returnValue));
    printf("with thread %ld\n", (long int) threadID);
  }
  // NOT REACHED
}
示例#13
0
ssize_t WriteFile(int filedes, const char *buffer, size_t nbytes){
    ssize_t n = write(filedes, buffer, nbytes);
    if(n!=nbytes)
        DieWithSystemMessage("write() failed");
    else
        return n;
}
示例#14
0
int Accept(int socket, sockaddr *clientAddress, socklen_t *addressLength){
	int n;
	n = accept(socket, clientAddress, addressLength);
	if(n<0)
		DieWithSystemMessage("accept() failed");
	return n;
}
示例#15
0
int Creat(const char *pathname){
    umask(0);
    int n = open(pathname, O_WRONLY | O_CREAT | O_TRUNC,RWRWRW);
    if(n == -1)
        DieWithSystemMessage("creat() failed");
    else
        return n;
}
示例#16
0
void SetCliServAddr(sockaddr_in *servaddr, const char *serverip){
	if(servaddr == NULL)
		DieWithSystemMessage("servaddr is error");
	bzero(servaddr, sizeof(*servaddr));
	servaddr->sin_family = AF_INET;
	servaddr->sin_port = htons(SERV_PORT);
	Inet_pton(AF_INET, serverip, &(servaddr->sin_addr));
}
示例#17
0
void SetServServAddr(sockaddr_in *servaddr){
	if(servaddr == NULL)
		DieWithSystemMessage("servaddr is error");
	bzero(servaddr, sizeof(*servaddr));
	servaddr->sin_family = AF_INET;
	servaddr->sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr->sin_port = htons(SERV_PORT);
}
示例#18
0
ssize_t Send(int socket, const void *msg, size_t msgLength, int flags){
	ssize_t n;
	n = send(socket, msg, msgLength, flags);
	if(n<0)
		DieWithSystemMessage("send() failed");   
	else if(n!=msgLength)
		DieWithUserMessage("send()", "sent unexpected number of bytes");
	return n;                                                                                                                                    
}
示例#19
0
int SetupTCPServerSocket(const char *service) {
  // Construct the server address structure
  struct addrinfo addrCriteria;                   // Criteria for address match
  memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure
  addrCriteria.ai_family = AF_UNSPEC;             // Any address family
  addrCriteria.ai_flags = AI_PASSIVE;             // Accept on any address/port
  addrCriteria.ai_socktype = SOCK_STREAM;         // Only stream sockets
  addrCriteria.ai_protocol = IPPROTO_TCP;         // Only TCP protocol



  struct addrinfo *servAddr; // List of server addresses
  int rtnVal = getaddrinfo(NULL, service, &addrCriteria, &servAddr);
  if (rtnVal != 0)
    DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));



  int servSock = -1;
  for (struct addrinfo *addr = servAddr; addr != NULL; addr = addr->ai_next) {
    // Create a TCP socket
    servSock = socket(addr->ai_family, addr->ai_socktype,
        addr->ai_protocol);
    if (servSock < 0)
      continue;       // Socket creation failed; try next address



    // Bind to the local address and set socket to listen
    if ((bind(servSock, addr->ai_addr, addr->ai_addrlen) == 0) &&
        (listen(servSock, MAXPENDING) == 0))
    {
      // Print local address of socket
      struct sockaddr_storage localAddr;
      socklen_t addrSize = sizeof(localAddr);


      if (getsockname(servSock, (struct sockaddr *) &localAddr, &addrSize) < 0)
        DieWithSystemMessage("getsockname() failed");


      fputs("Binding to ", stdout);
      PrintSocketAddress((struct sockaddr *) &localAddr, stdout);
      fputc('\n', stdout);

      break;       // Bind and listen successful
    }

    close(servSock);  // Close and try again
    servSock = -1;
  }

  // Free address list allocated by getaddrinfo()
  freeaddrinfo(servAddr);

  return servSock;
}
示例#20
0
int Inet_pton(int domain, const char *src, void *dst){
	int n;
	n = inet_pton(domain, src, dst);
	if(n==0)
		DieWithUserMessage("inet_pton() failed", "invalid address string");
	else if(n<0)
		DieWithSystemMessage("inet_pton failed");
	return n;
}
示例#21
0
int main(int argc, char *argv[]) {
  struct sigaction handler; // Signal handler specification structure

  // Set InterruptSignalHandler() as handler function
  handler.sa_handler = InterruptSignalHandler;
  // Create mask that blocks all signals
  if (sigfillset(&handler.sa_mask) < 0)
    DieWithSystemMessage("sigfillset() failed");
  handler.sa_flags = 0;  // No flags

  // Set signal handling for interrupt signal
  if (sigaction(SIGINT, &handler, 0) < 0)
    DieWithSystemMessage("sigaction() failed for SIGINT");

  for (;;)
    pause(); // Suspend program until signal received

  exit(0);
}
示例#22
0
文件: chat_help.c 项目: dcc635/chat
void chat_send(int sock, char *str) {
  size_t strLen = strlen(str); // Determine input length

  // Send the string to the server
  ssize_t numBytes = send(sock, str, strLen, 0);
  if (numBytes < 0)
    DieWithSystemMessage("send() failed");
  else if (numBytes != strLen)
    DieWithUserMessage("send()", "sent unexpected number of bytes");
}
示例#23
0
void Listen(int socket, int queueLimit){
	char *ptr;
	if( (ptr=getenv("LISTENQ")) !=NULL ){
		int limitMax = atoi(ptr);
		queueLimit = (limitMax<queueLimit)?limitMax:queueLimit;
	}
	
	if( listen(socket, queueLimit) < 0 )
		DieWithSystemMessage("listen() failed");
}
示例#24
0
char * HandleTCPClient(int clntSocket) {
   static char buffer[BUFSIZE]; // Buffer for echo string
    char *dlMode = "ttweet_REQUEST";
    // Receive message from client
    //printf("About to recv\n");
    ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
   // printf("Just recv'd recv\n");
    if (numBytesRcvd < 0)
        DieWithSystemMessage("recv() failed");
    
    //For Testing
    buffer[numBytesRcvd] = '\0';
    
    if(strcmp(dlMode, buffer)==0) {
	//same string
	//close(clntSocket);
	return buffer;
      
    }
    else {
    //fputs("Server recieved: ", stdout);
    //fputs(buffer, stdout);  
    // Send received string and receive again until end of stream
    while (numBytesRcvd > 0) { // 0 indicates end of stream
        // Echo message back to client
        ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0);
        if (numBytesSent < 0)
            DieWithSystemMessage("send() failed");
        else if (numBytesSent != numBytesRcvd)
            DieWithUserMessage("send()", "sent unexpected number of bytes");
        
        // See if there is more data to receive
        numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
	//printf("%i\n", numBytesRcvd);
        if (numBytesRcvd < 0)
            DieWithSystemMessage("recv() failed");
    }
    //printf("Closing now\n");
    close(clntSocket); // Close client socket
    return buffer;
    }
}
示例#25
0
文件: chat_help.c 项目: dcc635/chat
void chat_recv (int sock, char *str) {
  unsigned int totalBytesRcvd = 0;
  //char buffer[BUFSIZE]; // I/O buffer
  /* Receive up to the buffer size (minus 1 to leave space for
   a null terminator) bytes from the sender */
  int numBytes = recv(sock, str, BUFSIZE - 1, 0);
  if (numBytes < 0)
    DieWithSystemMessage("recv() failed");
  totalBytesRcvd += numBytes; // Keep tally of total bytes
  str[numBytes] = '\0';    // Terminate the string!
}
void HandleTCPClient(int clntSocket) {
  char     buffer[BUFSIZE]; // Buffer for echo string
  ssize_t  numBytesRcvd = 0;
  struct tm * timeinfo;
  time_t rawtime;
  ssize_t  bytesToSent = 0;
  // Receive message from client
  ssize_t totalBytes = recv(clntSocket, buffer, BUFSIZE, 0);
  if (totalBytes < 0)
    DieWithSystemMessage("recv() failed");

  // Send received string and receive again until you have recieved 4 bytes
  while (totalBytes < 4) { // 0 indicates end of stream
    numBytesRcvd = recv(clntSocket, buffer+totalBytes, BUFSIZE, 0);
    if(numBytesRcvd < 0)
      DieWithSystemMessage("recv() failed");

    totalBytes += numBytesRcvd;
  }

  buffer[totalBytes] = '\0';

  if(strcmp("date", buffer) == 0 ){
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer,80, "%T", timeinfo);
  }
  else if(strcmp("time", buffer) == 0){
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer,80, "%F", timeinfo);
  }

   ssize_t numBytesSent = send(clntSocket, buffer, strlen(buffer), 0);
   if (numBytesSent < 0)
      DieWithSystemMessage("send() failed");
   else if (numBytesSent != strlen(buffer))
      DieWithUserMessage("send()", "sent unexpected number of bytes");

  close(clntSocket); // Close client socket
}
int main(int argc, char *argv[]) {
  if (argc != 2) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)", "<Server Port/Service>");

  int servSock = SetupTCPServerSocket(argv[1]);
  // servSock is now ready to use to accept connections

  for (;;) { // Run forever

    // Wait for a client to connect
    int clntSock = AcceptTCPConnection(servSock);

    // Create an input stream from the socket
    FILE *channel = fdopen(clntSock, "r+");
    if (channel == NULL)
      DieWithSystemMessage("fdopen() failed");

    // Receive messages until connection closes
    int mSize;
    uint8_t inBuf[MAX_WIRE_SIZE];
    VoteInfo v;
    while ((mSize = GetNextMsg(channel, inBuf, MAX_WIRE_SIZE)) > 0) {
      memset(&v, 0, sizeof(v)); // Clear vote information
      printf("Received message (%d bytes)\n", mSize);
      if (Decode(inBuf, mSize, &v)) { // Parse to get VoteInfo
        if (!v.isResponse) { // Ignore non-requests
          v.isResponse = true;
          if (v.candidate >= 0 && v.candidate <= MAX_CANDIDATE) {
            if (!v.isInquiry)
              counts[v.candidate] += 1;
            v.count = counts[v.candidate];
          } // Ignore invalid candidates
        }
        uint8_t outBuf[MAX_WIRE_SIZE];
        mSize = Encode(&v, outBuf, MAX_WIRE_SIZE);
        if (PutMsg(outBuf, mSize, channel) < 0) {
          fputs("Error framing/outputting message\n", stderr);
          break;
        } else {
          printf("Processed %s for candidate %d; current count is %llu.\n",
              (v.isInquiry ? "inquiry" : "vote"), v.candidate, v.count);
        }
        fflush(channel);
      } else {
        fputs("Parse error, closing connection.\n", stderr);
        break;
      }
    }
    puts("Client finished");
    fclose(channel);
  } // Each client
  // NOT REACHED
}
void handle_Prompt(int clntSocket){
  char buffer[1]; // Buffer for prompt

  // Receive prompt (1-4) from client
  ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0);
  if (numBytesRcvd < 0)
    DieWithSystemMessage("recv() failed");

  int prompt = atoi[buffer];
  if(prompt == 1)
    cout << "F**K YEAH" << endl;
}
示例#29
0
文件: chat_help.c 项目: dcc635/chat
void chat_client_send(int sock, char *username, char *str) {
  char message[MSG_SIZE*2];
  sprintf(message, "%s: %s", username, str);
  size_t strLen = strlen(message); // Determine input length


  // Send the string to the server
  ssize_t numBytes = send(sock, message, strLen, 0);
  if (numBytes < 0)
    DieWithSystemMessage("send() failed");
  else if (numBytes != strLen)
    DieWithUserMessage("send()", "sent unexpected number of bytes");
}
示例#30
0
// Accept a new TCP connection on a server socket
int AcceptTCPConnection(int servSock) {
	struct sockaddr_storage clntAddr;
	// Set length of client address structure (in-out parameter)
	socklen_t clntAddrLen = sizeof(clntAddr);

	// Wait for a client to connect
	int clntSock = accept(servSock, (struct sockaddr*)&clntAddr, &clntAddrLen);
	if (clntSock < 0)
		DieWithSystemMessage("accpet() failed");

	// clntSock is connected to a client
	return clntSock;
}