Transfer image from client to server through socket tcp/ip

I try to finish my project winform apply in c#, I have this problem every time. The client should send a image to the server. And the server get the image and send to sql server,but the server not get anything I thing the problem is in the server side.

I tried to change the code a lot, I think the problem is in the server side.

connectioמ faild or the another side no respond correctly after time 10.0.0.8:10001

this is server side code:

    Socket hostSocket;
    Thread thread;
    string localIP = string.Empty;
    string computrHostName = string.Empty;
    private void btConnect_Click_1(object sender, EventArgs e)
    {
        computrHostName = Dns.GetHostName();
        IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in hostname.AddressList){
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                localIP = ip.ToString();
            }
        }
        this.Text = this.Text + " | " + localIP;
        connectSocket();
    }
    private void connectSocket()
    {
        Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse(localIP), 10011);
        //Connection node
        receiveSocket.Bind(hostIpEndPoint);
        receiveSocket.Listen(10);
        MessageBox.Show("start");
        hostSocket = receiveSocket.Accept();
        thread = new Thread(new ThreadStart(trreadimage));

        thread.IsBackground = true;
        thread.Start();
    }
    private void trreadimage()
    {
        int dataSize;
        string imageName = "Image-" + System.DateTime.Now.Ticks + ".JPG" ;
        try{
            dataSize = 0;
            byte[] b = new byte[1024 * 10000];  //Picture of great
            dataSize = hostSocket.Receive(b);
            if (dataSize > 0)
            {
                MemoryStream ms = new MemoryStream(b);
                Image img = Image.FromStream(ms);
                img.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
                pbimage.Image = img;
                ms.Close();
            }
        }

Upvotes: 0

Views: 2118

Answers (2)

Thanks you !!! , For you understanding my project is about apply that you can encrypt a message and to put into image (staganografia)and send as image to a recieve, we use a sql server to almancen info about the clients and if a client no conect , the server almacen the messages untill the client is on he cans see them , its a winform apply , if you know some example code , how client can to see the messages that he's recieves when he connected to server will be help for me to ...

Upvotes: 0

joehoper
joehoper

Reputation: 423

You're doing some interesting things with IP addresses and address families that I don't think are necessary -- you (probably) want your server to listen on all IP addresses, both IPv4 and IPv6.

When you're creating a MemoryStream from your byte array, it's always going to be 1024 * 10000 in length and this may confuse Image.FromStream as the rest end of the image will be padded with zeroes.

Here's my shot at a client that sends images (+filenames) to a server that saves the images to a folder. I'm using TcpClient + TcpListener instead of the more generic Socket class.

Server code:

class Program
{
    const int LISTENING_PORT = 10001;
    const string IMAGE_DIR = @"C:\Users\joehoper\Desktop\imgservtest\server\";
    const int BUFFER_SIZE = 10240;

    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Any, LISTENING_PORT);
        listener.Start();

        Console.WriteLine($"Listening on port {LISTENING_PORT}...");

        while (true)
        {
            var client = listener.AcceptTcpClient();
            Console.WriteLine($"Accepted client {client.Client.RemoteEndPoint}");
            ThreadPool.QueueUserWorkItem(cb => ClientThread(client));
        }
    }

    static void ClientThread(TcpClient client)
    {
        try
        {
            using (var stream = client.GetStream())
            {
                // Read filename length
                int fNameLen = stream.ReadByte();
                byte[] fNameBytes = new byte[fNameLen];

                // Read filename
                stream.Read(fNameBytes, 0, fNameLen);
                string fName = Encoding.Unicode.GetString(fNameBytes);

                using (var fs = File.OpenWrite(IMAGE_DIR + fName))
                {
                    byte[] buffer = new byte[BUFFER_SIZE];
                    while (true)
                    {
                        int r = stream.Read(buffer, 0, BUFFER_SIZE);
                        if (r == 0)
                            break;

                        fs.Write(buffer, 0, r);
                    }
                }
            }
        }

        finally
        {
            client.Close();
        }
    }
}

Client code:

class Program
{
    const string IMAGE_DIR = @"C:\Users\joehoper\Desktop\imgservtest\client\";
    const int CONNECT_PORT = 10001;
    const int BUFFER_SIZE = 10240;

    static void Main(string[] args)
    {
        Console.WriteLine("Press enter to start sending...");
        Console.ReadLine();

        foreach (string filename in Directory.GetFiles(IMAGE_DIR))
            SendImage(filename);
    }

    static void SendImage(string filename)
    {
        var client = new TcpClient("localhost", CONNECT_PORT);

        using (var cs = client.GetStream())
        {
            // Send filename
            byte[] fNameBytes = Encoding.Unicode.GetBytes(Path.GetFileName(filename));
            cs.WriteByte((byte)fNameBytes.Length);
            cs.Write(fNameBytes, 0, fNameBytes.Length);

            using (var fs = File.OpenRead(filename))
            {
                // Send image data
                byte[] buffer = new byte[BUFFER_SIZE];
                while (true)
                {
                    int r = fs.Read(buffer, 0, BUFFER_SIZE);
                    if (r == 0)
                        break;

                    cs.Write(buffer, 0, r);
                }
            }
        }

        client.Close();
    }
}

Upvotes: 2

Related Questions