读书人

Java和C#UDP通信有关问题

发布时间: 2013-06-25 23:45:41 作者: rapoo

Java和C#UDP通信问题
Java作为UDP的服务器,
C#做为UDP的客户端。
源代码


package com.taoge.socke;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPEchoServer {
private static final int ECHOMAX=255;//max size of echo datagram

public static void main(String[] args) throws IOException {
/*
if(args.length!=1){
throw new IllegalArgumentException("Parameter(s):<Port>");
}
*/
//int servPort=Integer.parseInt(args[0]);
int servPort = 5555;

//1.创建一个DatagramSocket实例,指定本地端口号,可以选择指定本地地址
DatagramSocket socket=new DatagramSocket(servPort);
DatagramPacket packet=new DatagramPacket(new byte[ECHOMAX],ECHOMAX);

while(true){
//2.使用DatagramSocket的receive方法来接收一个DatagramPacket实例。
socket.receive(packet);
System.out.println("Handling client at "+packet.getAddress().getHostAddress()+" on port "+packet.getPort());
System.out.println("包的数据:" + new String(packet.getData()));
socket.send(packet);
packet.setLength(ECHOMAX);
//socket.close();
}
}
}


C#部分


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApplication1
{

/**
* C# 版本UDP客户端,用与连接Java服务器端发送数据。
* */
class Program
{


static void Main(string[] args)
{
int SenderPort = 5555;
String host = "127.0.0.1";

IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipepoit = new IPEndPoint(ip,SenderPort);

UdpClient udpClient = new UdpClient(SenderPort);
udpClient.Connect(ip,SenderPort);

Byte[] sendByts = Encoding.ASCII.GetBytes("welcome to chengdu!!");

//udpClient.Send(sendByts,sendByts.Length);
udpClient.Send(sendByts, 255);
//IPEndPoint RemoteIpEndPoint = new IPEndPoint(ip, 0);

//Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
//string returnData = Encoding.ASCII.GetString(receiveBytes);

//Console.WriteLine("This is the message you received " + returnData.ToString());


//Console.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString());
Console.WriteLine("发送数据完毕!!");
udpClient.Close();

}
}
}



现在是C# 给Java发送消息,Java这段收不到消息。

Java给Java发送没有问题,C# 给C#发送也没有问题,现在就是C#发送给Java有问题。
[解决办法]
用mina做
[解决办法]
我喜欢用socket,原滋原味哈,Java没做修改,C#稍改了一下,Java端可以收到数据。


int SenderPort = 5555;
String host = "127.0.0.1";
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(host),SenderPort);

Byte[] sendByts = Encoding.ASCII.GetBytes("welcome to chengdu!!");
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SendTo(sendByts,sendByts.Length, SocketFlags.None, RemoteIpEndPoint);


Console.WriteLine("发送数据完毕!!");
socket.Close();

[解决办法]
应该消息是接收到的,只是C#发送过来时Java不知道哪里是消息帧的分界点而仍然缓存在消息队列里。

读书人网 >J2SE开发

热点推荐