【发布时间】:2016-09-02 14:09:57
【问题描述】:
我正在尝试将 Java 程序与 C# 程序进行通信,但它不起作用。
代码真的很基础,这里是:
这是 Java 客户端
static InetAddress ip;
static int port = 10000;
public static void main(String args[]) {
try {
ip = InetAddress.getByName("127.0.0.1");
DatagramSocket socket = new DatagramSocket(port, ip);
byte[] sendData = new byte[1024];
sendData = "Hola".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
socket.send(sendPacket);
socket.close();
} catch (Exception e) {
}
}
这里是 C# 服务器
static UdpClient client;
static IPEndPoint sender;
void Start () {
byte[] data = new byte[1024];
string ip = "127.0.0.1";
int port = 10000;
client = new UdpClient(ip, port);
sender = new IPEndPoint(IPAddress.Parse(ip), port);
client.BeginReceive (new AsyncCallback(recibir), sender);
}
static void recibir(IAsyncResult res){
byte[] bResp = client.EndReceive(res, ref sender);
//Convert the data to a string
string mes = Encoding.UTF8.GetString(bResp);
//Display the string
Debug.Log(mes);
}
c# 服务器是一个 Unity 文件,我的意思是,我从 Unity 执行它,所以 Start 是第一个调用的方法。
我希望他们通过我计算机中的端口 10000(或任何其他端口)进行通信,java 的 main 和 c# 的 start 似乎已执行,但从未调用回调。
关于它为什么不起作用的任何想法?谢谢大家。
【问题讨论】:
-
我也尝试在 c# 中使用阻塞接收,但从未收到消息。所以问题可能出在连接上,但我找不到。
标签: java c# udp communication