关于Android APP使用UDP无法接收服务器端回传数据

[复制链接]
查看11 | 回复0 | 2021-1-27 06:46:26 | 显示全部楼层 |阅读模式
最近用UDP传输的应用,用APP向服务器(公网)发送数据包,服务器接收到数据再回传数据给APP
但是出现了不知道怎么回事只能发,却收不到

APP的发送代码

privatevoidsetUdp()
{
//初始化socket端口
try{
if(this.socket==null)
{
this.socket=newDatagramSocket(null);
this.socket.setReuseAddress(true);
this.socket.bind(newInetSocketAddress(11000));
}
}catch(SocketExceptione){
e.printStackTrace();
}
try
{
this.serverAddress=InetAddress.getByName(SERVERIP);
}
catch(UnknownHostExceptione)
{
e.printStackTrace();
}
}
privatevoidlogin()
{

try
{
sendBuf=(login_username.getText().toString()+login_password.getText().toString()).getBytes("utf-8");
}
catch(Exceptione)
{
e.printStackTrace();
}
DatagramPacketpacketSend=newDatagramPacket(sendBuf,sendBuf.length,serverAddress,SERVERPORT);
try
{
//已发送完成
socket.send(packetSend);
System.out.println("Server:发送成功"+"’\n");
}
catch(Exceptione)
{
e.printStackTrace();
}
bytedata[]=newbyte[1024];
DatagramPacketpacketRec=newDatagramPacket(data,data.length);
try{
socket.receive(packetRec);
}catch(IOExceptione){
e.printStackTrace();
}
Stringresult=null;
try{
result=newString(packetRec.getData(),0,packetRec.getLength(),"utf-8");
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}
System.out.println("receiveclient'sdata:"+result);
}


下面是服务器接收代码
/**
*从UDP接收数据
*@return返回接收到的数据
*/
privatevoidTest()
{
RecByte=newbyte[1024];
try
{
DSRecPort=newDatagramSocket(9090);
}
catch(SocketExceptione)
{
e.printStackTrace();
}
DPRecPack=newDatagramPacket(RecByte,RecByte.length);//接收数据报实例
//接收数据包
try{
DSRecPort.receive(DPRecPack);
}
catch(IOExceptione)
{
e.printStackTrace();
}
//获取回传IP
InetAddressclientBAddress=DPRecPack.getAddress();
RecIp=clientBAddress.toString();
//获取回传端口
intclientBPort=DPRecPack.getPort();
RecPort=Integer.toString(clientBPort);
//测试创建发送端口
try
{
if(this.DSSendPort==null)
{
DSSendPort=newDatagramSocket(null);
DSSendPort.setReuseAddress(true);
DSSendPort.bind(newInetSocketAddress(9091));
}
}
catch(SocketExceptione)
{
e.printStackTrace();
}
Stringa="true";
DPSendBytePack=newDatagramPacket(a.getBytes(),a.getBytes().length,clientBAddress,clientBPort);
try{
//使用接收端端口回传,手机接收成功
DSRecPort.send(DPSendBytePack);
//------------------------使用其他端口回传,手机接收失败--------------------------------????????????
//DSSendPort.send(DPSendBytePack);
}
catch(IOExceptione)
{
e.printStackTrace();
}
//为什么上面只能从接收端口的对象发送,而创建其他端口的发送对象手机接收不到数据
}


//为什么上面只能从接收端口的对象发送,而创建其他端口的发送对象手机接收不到数据
分 -->
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行