开发者

How to send data from c# client to java server via socket?

开发者 https://www.devze.com 2022-12-17 13:26 出处:网络
I have a socket sever is written by java, it always listens on specific port. I wrote a client in Java and it could connect to the server but when I created a client in C#, I could not connect to Serv

I have a socket sever is written by java, it always listens on specific port. I wrote a client in Java and it could connect to the server but when I created a client in C#, I could not connect to Server.

I just want to send a short value to start a java server.

I guess the problem come from the endianess (little-endian, big-endian) and I have several days to research but can not solve this issue.

I post more information about my problem

I use java.io.* and java.net.*. My java code

out = new ObjectOutputStream(requestSocket.getOutputStream());

out.flush();

public static final short CLIENT = 0;

out.writeShort(CLIENT);

out.flush();

and with c#, I use System.Net.Sockets. My C# code is below:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

...

short sClient = 0;

if (BitConverter.IsLittleEndian) sClient = IPAddress.HostToNetworkOrder(sClient);

NetworkStream ns = new NetworkStream(socket);

BinaryWriter bw = new BinaryWriter(ns);

bw.Write(sClient);

The java code can connect to the java server but the c# code can not :(. The output error from java server is "Excepti开发者_Go百科on while getting socket streams"

Anyone can help me about this problem, thanks in advance


If endianness is your problem you should have a look at the following two links which show you how to convert between Host and Network Byte order

Network to Host order

Host to network order

Hope this helps.


A server is a server, so you're going to need to be more specific. There could be a million reasons they aren't communicating correctly. Can you ping the machine the service is on? Are they running on the same machine or might there be firewall issues? Are you debugging each to see if the request is timing out or being actively denied? Are they connecting but the encoding is wrong?

Also, what protocols are you using? If you're sending binary data in a custom protocol format, endianess might be a worry, but most protocols expect network byte order. If there is an endianess problem, that's something you'd need to verify in a debugger. What calsses are you using in Java and .NET? Can you post some sample code?

More information is necessary to solve this.

0

精彩评论

暂无评论...
验证码 换一张
取 消