【问题标题】:TCP server and Browser as Web client in CTCP服务器和浏览器作为C中的Web客户端
【发布时间】:2017-03-02 17:34:58
【问题描述】:

程序:

//Server

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<netdb.h>
void main()
{
    int fd=socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in sa,clientaddr;
    struct in_addr ip;

    if(inet_pton(AF_INET,"127.0.0.1",&ip)!=1){
        perror("inet_pton");
        exit(1);
    }

    sa.sin_family=AF_INET;
    sa.sin_port=htons(5000);
    sa.sin_addr=ip;

    if(bind(fd,(struct sockaddr*)&sa,sizeof(sa))!=0){
        printf("Unable to Bind\n");
        perror("");
        exit(1);    
    }

    if(listen(fd,1024)!=0){
        printf("Unable to Listen \n");
        exit(1);
    }
    int len=sizeof(struct sockaddr);
    int des;
    if((des=accept(fd,(struct sockaddr*)&clientaddr,&len))<0){
        printf("Unable to accept\n");
    }
    else{
        printf("Connection accepted....\n");

        char buf[1024];

        int r=recv(des,buf,1024,0);
        printf("Recived Data: ");
        fflush(stdout);
        write(1,buf,r);
        printf("\n");
        buf[0]='\0';
    }
}

上述程序是简单的服务器程序,它接受客户端连接并接受客户端发送的数据。我做实验 使用 telnet 如下所示。

服务器:

$ ./a.out 
Connection accepted....
Recived Data: ...Hai...
$

客户:

$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
...Hai...
Connection closed by foreign host.
$

使用 telnet 时,它可以正常工作。但我的要求不是连接到telnet,而是连接到浏览器。我检查 使用浏览器作为我的客户端,例如“127.0.0.1:5000”。我希望建立任何连接。但是没有响应和服务器进程 没有收到任何请求。这背后有什么问题。为什么服务器没有收到请求?

与 telnet 类似,浏览器也获取 ip 和端口号并建立 TCP 连接。但它不起作用。谁能解释一下为什么会这样 这 ?

【问题讨论】:

  • 您在使用浏览器时没有看到“已接受连接...”消息吗?请使用 tcpdump 来查看线路上发生的情况

标签: c linux sockets unix network-programming


【解决方案1】:

Telnet 将输出您发回给它的任何内容,但浏览器在呈现之前希望得到完整的 HTTP/1.1 响应。 它会是这样的(\r\n 很棘手):

header = "HTTP/1.1 200 OK\r\n" 
         + "Content-Type: text/html;charset=UTF-8\r\n" 
         + "\r\n";

然后是您希望浏览器呈现的任何内容。

这解决了您的部分问题,我不知道为什么您在服务器端看不到浏览器请求(通常是“GET / HTTP/1.1”或类似的东西),我会尝试更改服务器不要在单个请求后退出(放入 while(1) 循环,看看会发生什么)。

while(1){
    if((des=accept(fd,(struct sockaddr*)&clientaddr,&len))<0){
        printf("Unable to accept\n");
    }
    else{
        printf("Connection accepted....\n");

        char buf[1024];

        int r=recv(des,buf,1024,0);
        printf("Recived Data: ");
        fflush(stdout);
        write(1,buf,r);
        printf("\n");
        buf[0]='\0';
    }
    close(des);
}

【讨论】:

  • 还是不行...在发送标头之前,它会启动连接。建立连接后,仅发送标头。
猜你喜欢
  • 2016-04-10
  • 1970-01-01
  • 2019-02-26
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多