Question

Java (client side)

relevant code

    // Create the encoder and decoder for targetEncoding
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    CharsetEncoder encoder = charset.newEncoder();
    byte[] underlyingBuffer = new byte[100000];
    ByteBuffer buffer = ByteBuffer.wrap(underlyingBuffer);

    System.out.println("first buffer remaining" + buffer.remaining() + " "
            + buffer.limit());
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    try {
        Socket client = new Socket("localhost", 8080);

        OutputStream oStream = client.getOutputStream();
        InputStream iStream = client.getInputStream();


        //String secondFilePath = "C:\\Users\\pedge\\Desktop\\readData.csv";//this is csv file
        //long secondFileLength = ReadFileToCharArray(buffer,secondFilePath , encoder);

                    String inputImage = "C:\\Users\\pedge\\Desktop\\Desert.jpeg";// image to transfer           
                    ReadFileToCharArray(buffer,inputImage , encoder);
        //imageWrite(oStream, inputImage);

        buffer.flip();

        int dataToSend = buffer.remaining();

        int remaining = dataToSend;

        while (remaining > 0) {
            oStream.write(buffer.get());
            --remaining;
        }

public static long ReadFileToCharArray(ByteBuffer buffer, String filePath,
        CharsetEncoder encoder) throws IOException {
            fileCount++;
    System.out.println("second buffer remaining" + buffer.remaining() + " "
            + buffer.limit());

    StringBuilder fileData = new StringBuilder(100);
    File file = new File(filePath);
            System.out.println("Size of file ["+fileCount+"] sent is ["+file.length()+"]");

    BufferedReader reader = new BufferedReader(new FileReader(filePath));

    char[] buf = new char[10000000];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        System.out.println(numRead);
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1000000];
    }

    reader.close();
    CharBuffer charBuffer = CharBuffer.wrap(fileData.toString()
            .toCharArray());
    System.out.println("char buffer " + charBuffer.remaining());

    ByteBuffer nbBuffer = null;
    try {
        nbBuffer = encoder.encode(charBuffer);

    } catch (CharacterCodingException e) {
        throw new ArithmeticException();
    }

    buffer.putInt(nbBuffer.limit());
    System.out.println("buffer information" + buffer.position() + " "
            + buffer.limit() + " nbBuffer information" + nbBuffer.position()
            + " " + nbBuffer.limit());
    buffer.put(nbBuffer);
    return file.length();
}

C# (Server Side)

        static void Main(string[] args)
    {
        try
        {
            Run(args);
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e);
        }

    }

   static void Run(string[] args)
    {
        TcpListener listener = new TcpListener(8080);
        listener.Start();

        while (true)
        {
            using (TcpClient client = listener.AcceptTcpClient())
            {
                try
                {
                    Read(client);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                }
            }
        }
    }
static void Read(TcpClient client)
    {
        String csvFile4Parsing = "C:\\Users\\pedge\\Desktop\\newReadData.csv";// csv file created from byte stream

        Console.WriteLine("Got connection: {0}", DateTime.Now);
        NetworkStream ns = client.GetStream();
        BinaryReader reader = new BinaryReader(ns);


        int length = reader.ReadInt32();
        Console.WriteLine("Length of csv is [" + length + "]");
        byte[] fileArray = reader.ReadBytes(length);
        File.WriteAllBytes(csvFile4Parsing, fileArray);//bytes from stream, written to csv`

Now i am able to transfer the image from java to C# and a file is then created by c#(works perfect)

But when i try to send the image(same as like CSV), it doesn't work at all and even the bytes received at the server end are different from that of client end. I have spent hours now on this with no success. :/

and help will be much appreciated. thanks.

Was it helpful?

Solution 2

Finally the solved this issue.

Java(Client)

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class ImageServer {
    public static void main(String[] args) {
        try {


        Socket socket = new Socket("localhost", 8000);

        //code to send image
        File file = new File("C:\\Users\\ashish\\Desktop\\image.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        int count=0;
        byte[] fileBytes = new byte[(int)file.length()];

        int content;
        OutputStream outputStream = socket.getOutputStream();

        while((content = fileInputStream.read(fileBytes)) != -1){
            outputStream.write(fileBytes, 0, (int)file.length());               
        }

        System.out.println("file size is "+ fileBytes.length);
        for(byte a : fileBytes){System.out.println(a);}           

    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
}

C#(Server)

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Test.SendImageClient
{
    public class Program
    {
        static void Main(string[] args)
        {
            TcpListener tcpListener = null;
            try
            {
                IPAddress ipadress = IPAddress.Parse("127.0.0.1");
                 tcpListener = new TcpListener(ipadress, 8000);

                /* Start Listeneting at the specified port */
                tcpListener.Start();
                byte[] bytes = new byte[6790];
                byte[] finalBytes;

              while(true){
                  TcpClient client = tcpListener.AcceptTcpClient();
                  Console.WriteLine("Connected!");
                  NetworkStream stream = client.GetStream();

                  int i;

                  do
                  {
                      i = stream.Read(bytes, 0, bytes.Length);
                      finalBytes = new byte[i];
                      Console.WriteLine("Size dynamically is "+i);
                      for (int n = 0; n < i; n++ )
                      {
                          finalBytes[n] = bytes[n];
                      }                     
                  }while(stream.DataAvailable);

                  File.WriteAllBytes("C:\\Users\\ashish\\Desktop\\newImage.jpg", finalBytes);

                  client.Close();
              }                
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                tcpListener.Stop();
            }

        }
    }
}

OTHER TIPS

CSV data is text and might require the CharsetEncoder you are using to process the stream before sending it to the C#, but image data is binary and you only want to send a bit-for-bit copy of the data. The problem is likely to be that the stream encoder mistakenly interprets some binary sequences in the image data as text characters that need to be encoded and mangles them.

Just use plain binary stream read and write on both sides (you are already doing it in C#) and confirm that the data is exactly the same. If it isn't, post a hex sample of how it is different.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top