有个JAVA与dotnet使用UDP通讯的问题,向牛人讨教.
阿牛在线 2007-06-07 04:05:29 因应用需要,服务器端代码需要用C#编写,而客户端要用JAVA开发.
C# Server使用UDP进行数据报广播后,JAVA Client 得到数据报,并输出,可是遇到的问题是C#中的Byte[] 型数据用JAVA的DatagramPacket 数据结构没办法正确读取,急需帮助.
C# Server端的代码:
public static void SendCommand(string command)
{
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);//255.255.255.255
string hostname = Dns.GetHostName();
command = Coder.Encrypt(command);
byte[] data = Encoding.UTF8.GetBytes(command);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sock.SendTo(data, iep1);
sock.Close();
}
JAVA 接收广播的代码.
try
{
byte[] buf = new byte[1024];
byte[] buf1 = new byte[1024];
DatagramSocket ds = new DatagramSocket(9050);
DatagramPacket ip = new DatagramPacket(buf,buf.length);
ByteArrayInputStream bytestream = null;
ObjectInputStream objstream = null;
String mess = "";
while(true)
{
ds.receive(ip);
buf1 = ip.getData();
mess = new String(buf1,"UTF-8");
System.out.println(mess);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}