简体   繁体   English

如何使用C#从套接字检索Java数据?

[英]How can I use C# to retrieve Java data from a socket?

I want to send BigInteger data in socket and my friend wants to retrieve the data. 我想在套接字中发送BigInteger数据,而我的朋友想检索该数据。
I am using Java, but my friend uses C#. 我使用Java,但我的朋友使用C#。

String str = "Hello";
BigInteger big = new BigInteger(str.getBytes);
byteToBeSent[] = big.toByteArray();

I am sending this byte array ( byteToBeSent[] ) through socket. 我正在通过套接字发送此字节数组( byteToBeSent[] )。 And my friend wants to retrieve "Hello". 我的朋友想检索“你好”。

How is this possible? 这怎么可能?

From Java, send your string using String.getBytes(encoding) and specify the encoding to match how your friend will read it (eg UTF-8). 从Java,使用String.getBytes(encoding)发送您的字符串,并指定编码以匹配您的朋友如何读取它(例如UTF-8)。

This will translate your string into a byte stream that will be translatable at the C# end due to the fact that you're both agreeing on the encoding mechanism. 由于您都同意编码机制,因此这会将您的字符串转换为可在C#端翻译的字节流。

I'm not sure what your BigInteger mechanism is doing, but I don't believe it'll be portable, nor handle sizable strings. 我不确定您的BigInteger机制在做什么,但是我不认为它会是可移植的,也不会处理可观的字符串。

Honestly, your best bet would to be use the built in Encoding classes in C#. 老实说,最好的选择是使用C#中内置的Encoding类。

string str = "Hello";
byte[] data = System.Text.Encoding.UTF8.GetBytes(str);

And then send that through the socket. 然后通过套接字发送。

Why do you use BigInteger to send String data? 为什么使用BigInteger发送String数据? Or is that just an example? 还是只是一个例子?

If you want to send String data, use String.getBytes(String encoding) , send the result and decode it using System.Text.Encoding . 如果要发送String数据,请使用String.getBytes(String encoding) ,发送结果并使用System.Text.Encoding对其进行解码。

You'll need to get a custom BigInteger class for C# . 您需要为C#获取自定义BigInteger类

But parsing "Hello" as a biginteger isn't going to work. 但是将“ Hello”解析为biginteger是行不通的。 I you want to send text, you're better of using Navaars method. 我想发送文本,最好使用Navaars方法。

On the C# end, you can use System.Text.Encoding.ASCII.GetString(bytesToConvert[]) to convert the received byte array back to a string. 在C#端,可以使用System.Text.Encoding.ASCII.GetString(bytesToConvert [])将接收到的字节数组转换回字符串。

I had thought that was some sort of Java idiom to convert a string to a byte array. 我以为这是将字符串转换为字节数组的某种Java习惯用法。 It does correctly convert the string into ASCII bytes, and since BigInteger length is arbitrary, the length of the string should not be an issue. 它确实可以将字符串正确转换为ASCII字节,并且由于BigInteger的长度是任意的,因此字符串的长度应该不成问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM