繁体   English   中英

当 C 中的字符串为“时间”时,如何打印当前时间?

[英]How can i print current time when string is "Time" in C?

我正在开发一个 c 程序,该程序发送消息并从服务器获取消息,但如果字符串是“时间”,我想将时间发送给 EchoClient。 我该怎么做?

我曾尝试使用一些代码,但对于我的知识来说它们似乎太复杂了。有人知道该怎么做吗? EchoClient.c

#include "nethelp.h"

int main(int argc, char **argv) 
{
    int clientfd, port;
    char *host, buf[MAXLINE];
    int n;

    if (argc != 3) {
    fprintf(stderr, "usage: %s <host> <port>\n", argv[0]);
    exit(0);
    }
    host = argv[1];
    port = atoi(argv[2]);

    clientfd = open_clientfd(host, port);

    while (fgets(buf, MAXLINE, stdin) != NULL) {
    write(clientfd, buf, strlen(buf));
    n = readline(clientfd, buf, MAXLINE);
    write(1, buf, n);
    }
    close(clientfd);
    exit(0);
}

EchoServer.c

#include "nethelp.h"

void echo(int connfd);
void *thread(void *vargp);

int main(int argc, char **argv) 
{
    int listenfd, *connfdp, port, clientlen=sizeof(struct sockaddr_in);
    struct sockaddr_in clientaddr;
    pthread_t tid; 

    if (argc != 2) {
    fprintf(stderr, "usage: %s <port>\n", argv[0]);
    exit(0);
    }
    port = atoi(argv[1]);

    listenfd = open_listenfd(port);
    while (1) {
    connfdp = malloc(sizeof(int));
    *connfdp = accept(listenfd, (struct sockaddr*)&clientaddr, &clientlen);
    pthread_create(&tid, NULL, thread, connfdp);
    }
}

void * thread(void * vargp) 
{  
    int connfd = *((int *)vargp);
    pthread_detach(pthread_self()); 
    free(vargp);
    echo(connfd);
    close(connfd);
    return NULL;
}


void echo(int connfd) 
{
    size_t n; 
    char buf[MAXLINE]; 

    while((n = readline(connfd, buf, MAXLINE)) != 0) {
    printf("server received %d bytes\n", n);
    write(connfd, buf, n);
    }
}

要将当前时间作为文本发送,

if (strcmp(buf, "time")== 0) {
  time_t now;
  time(&now);  // Get the current time
  if (now == -1) Handle_Error();
  struct tm *tm;
  tm = gmtime(&now); // Convert to a time struct (YMD HMS etc.) as if Universal time
  if (tm == NULL) Handle_Error();
  char buf[100];
  // See strftime and ISO 8601 for format details
  // Convert  from a time struct to a string
  if (strftime(buf, sizeof buf, "%FT%T") == 0) Handle_Error();
  send(buf);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM