error when using TcpSocket

zsxxsz zhengshuxin at hexun.com
Sat May 16 08:09:29 PDT 2009


I rewrote the code as below:

import std.c.string;
import core.stdc.errno;
import std.stdio;
import std.socket;
import std.stream;
import std.socketstream;

import core.sys.posix.netinet.in_;
class CSocket: Socket
{
public:
        this(AddressFamily family)
        {
                super(family, SocketType.STREAM, ProtocolType.TCP);
        }
        this()
        {
                this(cast(AddressFamily)AddressFamily.INET);
        }
        void connect(string ip, ushort port)
        {
                sockaddr_in sin;

                sin.sin_family = AF_INET;
                sin.sin_port = htons(port);
                sin.sin_addr.s_addr = inet_addr("127.0.0.1");

                int ret = .connect(handle, cast(sockaddr*) &sin, sin.sizeof);
                if (ret == -1)
                        throw new SocketException("Unable to connect socket");
        }
}

Socket sock_connect(string addr, ushort port)
{
        Socket sock;
        Address address = new InternetAddress(addr, port);

        try {
                sock = new TcpSocket(address);
        } catch (Exception e) {
                throw e;
        }
        return (sock);
}

Socket sock_connect2(string add, ushort port)
{
        CSocket sock = new CSocket();

        try {
                sock.connect("127.0.0.1", 80);
        } catch (Exception e) {
                throw e;
        }

        return (sock);
}
void test_socket(string addr, ushort port)
{
        Socket sock;

        try {
                //sock = sock_connect2(addr, port);
                sock = sock_connect(addr, port);
        } catch (Exception e) {
                throw e;
        }

        Stream ss = new SocketStream(sock);

        writefln("socket: %d", sock.handle());

        try {
                ss.writeString("GET / HTTP/1.0\r\n\r\n");
        } catch (Exception e) {
                printf("error: %s\n", strerror(errno));
                throw e;
        }

        while (!ss.eof) {
                char[] line;

                try {
                        line = ss.readLine();
                } catch (Exception e) {
                        printf("error: %s\n", strerror(errno));
                        throw e;
                }
                writefln("%s", line);
        }
}

int main(string[] args)
{
        test_socket("127.0.0.1", 80);
        return (0);
}

when use myown socket class and call sock_connect2(), I can get the correct
result. But when I use the TcpSocket of phobos2.029, I get one error as
"std.stream.WriteException: unable to write to stream".
Why?
Thanks
zsxxsz


More information about the Digitalmars-d-learn mailing list