我正在尝试从服务器端口2020读取一些数据包。我运行了tcpdump -r eth1端口2020,可以发现udp数据包正在进入端口。以下是截图:
但是当我尝试从java代码中读取这些数据包时,我没有得到任何数据。以下是我的java代码:
package packetreceiver;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import main.Main;
import propertyfilereader.PropertyFileReader;
import org.apache.log4j.Logger;
import com.sun.jmx.snmp.SnmpMessage;
import alarmprocessor.AlarmProcessor;
public class UDPPacketReceiver extends Thread {
private DatagramSocket socket = null;
private Logger logger = Logger.getLogger(UDPPacketReceiver.class);
public boolean dynamicKey = false;
private UDPPacketReceiver() {
try {
logger.debug(" port : " + Main.orgPort);
logger.debug(" ip : " + Main.orgBindIPStr);
logger.debug("creating socket");
socket = new DatagramSocket(null);
//socket = new DatagramSocket(38567);
InetSocketAddress address = new InetSocketAddress(2020);
socket.bind(address);
logger.debug("Receiver Socket created successfully");
} catch (Exception e) {
logger.fatal("Exception at creating socket ", e);
logger.fatal("Exiting successfully ");
System.exit(0);
}
this.running = true;
}
static UDPPacketReceiver instance = null;
public static UDPPacketReceiver getInstance() {
if (instance == null) {
createInstance();
}
return instance;
}
boolean running = false;
private static synchronized UDPPacketReceiver createInstance() {
if (instance == null) {
instance = new UDPPacketReceiver();
}
return instance;
}
public void run() {
byte[] data = new byte[2048];
DatagramPacket packet = new DatagramPacket(data, data.length);
while (this.running) {
try {
logger.debug("waiting for received data");
this.socket.receive(packet);
int length = packet.getLength();
logger.debug("length:"+length);
logger.debug("data:"+new String(packet.getData()));
} catch (Exception e) {
if ((this.socket == null) || (this.socket.isClosed())) {
this.running = false;
} else {
this.logger.fatal("Error in receiving UDP packet:", e);
}
}
}
}
public void shutdown() {
this.running = false;
try {
if ((this.socket != null) && (!this.socket.isClosed())) {
this.socket.close();
}
} catch (Exception localException) {
}
this.socket = null;
}
}
我在stackeoverflow和其他帖子中搜索过但找不到任何解决方案。你能帮我吗?
此致 坦维尔
答案 0 :(得分:0)
使用netstat命令检查您的应用程序是否实际绑定到正确的IP /接口:
> sudo netstat -tunlp | grep 2020
在linux中运行。
您也可以更改此行:
InetSocketAddress address = new InetSocketAddress(172.22.49.116, 2020);