如何在C#客户端和Java

如何在C#客户端和Java

本文介绍了如何在C#客户端和Java Server之间传输图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个包含C#客户端和Java(SE)服务器的项目,使用socket(tcp)进行通信。当客户端发送字符串或整数信息时,它工作正常,服务器可以完美地收到确切的信息。但是,我现在无法将图像从客户端发送到服务器或以可逆方式发送。我想出了一种可能的方法,将图像传输到字节数组并通过套接字发送字节数组,服务器收到后,服务器再次将数组传输到图像。这听起来可行,但在我实现和调试之后,部分字节数组被损坏了。请注意,C#-byte的范围是[0,255]而Java字节的范围是[-128,127]。因此,当一个大于128的C#字节传输到Java端时,它就会被损坏。

请帮助我,如果你提供一种传输图像的方法,它会受到关注在C#和Java之间。

I'm working on a project that contains a C# client and a Java(SE) server, using socket (tcp) for communication. When the client send string or integer information, it work just fine, the server can perfectly recieve the exact information. However, I'm now in trouble sending images from the client to the server or in the reversive way. I came up with a probable way by transferring the image to a byte array and send the byte array through socket and after the server recieves it, the server transfers the array to an image again. It sounds doable but after I implemented and debugged this, part of the byte array was "damaged". Note that a C#-byte's range is [0,255] while a Java-byte's range is [-128,127]. So when a C#-byte that is greater than 128 is transmitted to the Java side, it is "damaged".
Please help me out, it'll be apprieciated if you provide a way to transmit images between C# and Java.

推荐答案



public static byte[] ImageToBytes(string path)
        {
            FileInfo fileInfo = new FileInfo(path);
            byte[] buffer = new byte[fileInfo.Length];
            using (FileStream stream = fileInfo.OpenRead())
            {
                stream.Read(buffer, 0, buffer.Length);
            }
            return buffer;
        }




public static bool sendBytes(byte[] content)
        {
            try
            {
                int length = content.Length;
                sendCode(length);
                clientSocket.Send(content);
                return true;
            }
            catch
            {
                return false;
            }
        }





Java:



Java:

public static void byte2image(byte[] data, String path) {
		if (data.length < 3 || path.equals(""))
			return;
		try {
			FileImageOutputStream imageOutput = new FileImageOutputStream(
					new File(path));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
			System.out.println("Make Picture success,Please find image in "
					+ path);
		} catch (Exception ex) {
			System.out.println("Exception: " + ex);
			ex.printStackTrace();
		}
	}




public static byte[] readBytes(){
		DataInputStream din=null;
		int length=readCode();
		byte[] b=new byte[length];
		try {
			din = new DataInputStream(socket.getInputStream());
			din.read(b);
			din.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}


这篇关于如何在C#客户端和Java Server之间传输图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:47