D - 将数据发送到套接字

时间:2012-12-11 20:21:05

标签: 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;
}

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

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

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

2 个答案:

答案 0 :(得分:5)

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

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

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

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

答案 1 :(得分: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 --

更新:我已经重新检查了 win64 下的代码段,我对 内容类型 的猜测似乎对。如果您将内容声明为 text / html ,则应提供有效的HTML,即

<html><body>Hi from D!</body></html>

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

请注意,我只在Windows上获得这种行为,即在Linux上,您的代码片段按原样运行(使用ff,telnet等)。

相关问题