D - 将数据发送到套接字

1 sockets d send

我在D中有以下原始服务器:

import std.stdio; 
import std.socket; 

int main() {

const int port = 8080; 

InternetAddress addr = new InternetAddress(InternetAddress.ADDR_ANY, port); 
TcpSocket server = new TcpSocket(AddressFamily.INET); 

server.bind(addr); 
server.listen(10);


for(;;) {

    Socket newclient = server.accept(); 

    newclient.send("HTTP/1.1 200 OK\r\n"); 
    newclient.send("Content-type: text/html\n\n"); 
    newclient.send("Hi from D!");

    newclient.shutdown(SocketShutdown.BOTH); 
    newclient.close(); 
}



    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我使用浏览器连接,它不会显示"Hi From D!",而只是断开连接.

我的假设是send()缓冲数据,我必须刷新该缓冲区.但我还没弄明白你会怎么做.有趣的是,如果用writefln("asdf asdf \n")将一些数据写入STDOUT,代码就可以工作; 在send()的最后一次调用之后,因此我的假设.

还是我在错误的树上吠叫?

Ada*_*ppe 5

你的代码实际上对我有用....但是一些可能有帮助的改变:

1)在响应中添加Content-length头

2)使用\ r \n\r \n结束标题而不是\n \n.

如果这些没有帮助,它也可能是防火墙或类似阻止您的连接的问题.


bar*_*ddu 5

这可能是一个标题问题,尝试类似于:

// -- cut --

Socket newclient = server.accept(); 

newclient.send("HTTP/1.1 200 OK\r\n"); 
newclient.send("Content-type: text/plain\r\n"); 
newclient.send("Connection: close\r\n\r\n");
newclient.send("Hi from D!\r\n");

newclient.shutdown(SocketShutdown.BOTH); 
newclient.close();

// -- cut --
Run Code Online (Sandbox Code Playgroud)

更新:我已经重新检查代码段下Win64的和我有关的猜测内容类型似乎是正确的.如果您将内容声明为text/html,即应提供有效的html,即

<html><body>Hi from D!</body></html>
Run Code Online (Sandbox Code Playgroud)

或提供正确的contnet类型(即text/plain).

请注意,我只在Windows上获得这种行为,即在Linux上,您的代码片段可以正常工作(使用ff,telnet等).