Sending messages using socket
nrgyzer
nrgyzer at gmail.com
Mon Jul 25 07:34:38 PDT 2011
== Auszug aus Adam Ruppe (destructionator at gmail.com)'s Artikel
> Browsers speak HTTP, which is a higher level protocol than
> plain sockets.
> If you connect to your app with a simpler program, like nc,
> you'll probably see the message.
> If you want to serve web pages, consider one of these options:
> a) Looking up the HTTP protocol itself. You've gotta send headers
> before you send data or the browser won't understand what you are
> replying to.
> b) Use an existing web server, like Apache, and write your app as
> a cgi program
> The HTTP headers you need to send on a plain socket look like this:
> =====
> HTTP/1.0 200 OK
> Content-Length: 11
> Content-Type: text/html
> hello world
> =====
> instead of just plain "hello world".
The message exchange works, but I've some trouble in getting the messages correctly. I've the following, small apps:
module server;
import std.socket;
import std.stream;
import std.socketStream;
void main() {
TcpSocket s = new TcpSocket();
s.bind(new InternetAddress(5088));
s.listen(1);
while(true) {
Socket a = s.accept();
SocketStream cs = new SocketStream(a);
string response = "HELLO WORLD!";
cs.writeBlock(response.ptr, response.length);
a.close();
}
}
module client;
import std.socket;
import std.math;
import std.stream;
import std.socketStream;
import std.stdio : writeln;
void main() {
TcpSocket s = new TcpSocket();
s.connect(new InternetAddress("127.0.0.1", 5088));
while(true) {
void[] msg;
SocketStream cs = new SocketStream(s);
cs.readBlock(msg.ptr, 12);
writeln(msg);
}
}
But... when I start the server and client, I don't get any response/and or my message is empty. When I use the simply methods of streams
(like write()), it works but the problem is, that the following will end in an endless loop:
module client;
import std.socket;
import std.math;
import std.stream;
import std.socketStream;
import std.stdio : writeln;
void main() {
TcpSocket s = new TcpSocket();
s.connect(new InternetAddress("127.0.0.1", 5088));
while(true) {
uint len;
string msg;
SocketStream cs = new SocketStream(s);
while(!cs.eof()) { // this loop repeats forever, although the stream is empty
cs.read(len);
cs.readString(msg, len);
}
}
}
More information about the Digitalmars-d-learn
mailing list