I want to write a chat server. Using the programming language D. (Dlang) It is desirable to use OOP.

My example.(Not working)

import std.stdio;
import std.concurrency;
import core.thread;
import std.conv;
import std.socket;

synchronized class DataInfo{
    shared this()
    {
    }
    public shared Socket[] sockList;
    shared void AddSocket(shared Socket scket)
    {
        sockList ~= scket;
    }

    shared(Socket[]) getSockList()
    {
        return to!(shared Socket[])(sockList);
    }
}
void UserLoop(shared DataInfo data,shared(int) id)
{
    Socket client;
    synchronized(data)
    {
        client = cast(Socket)(data.sockList[id]);
    }

    while(true)
    {
        char[1024] buffer;
        int sockCount = 0;
        client.receive(buffer);
        synchronized(data)
        {
            sockCount = data.sockList.length;
        }

        for(int i =0 ; i < sockCount; i++)
        {
            synchronized(data)
            {
                auto sk = cast( Socket)(data.sockList[i]);
                sk.send("Hello world");
            }
        }
    }
}

int main()
{

        ushort port;
        port = 4444;

        auto listener = new TcpSocket();
        assert(listener.isAlive);
        listener.blocking = false;
        listener.bind(new InternetAddress(port));
        listener.listen(10);
        writefln("Listening on port %d.", port);
        shared(DataInfo) data = new shared(DataInfo);
        while(true)
        {
            int len = 0;
            auto client = cast(shared Socket)listener.accept();
            synchronized(data)
            {
                data.AddSocket(client);
                len = data.sockList.length;
            }
            spawn(&UserLoop,data,cast(shared int)len);
        }
        return 0;
}
How? How to fix the bug? Can I get an example of correct chat servers? (Only Dlang & (Hadoop)[https://mindmajix.com/hadoop-training]) Also, can you give an example of the correct client.

Help me on this!

Reply via email to