我有这个代码,我通过Android手机接收数据
public void run() {
try {
while(true) {
final String hey;
int server_port = 9875;
byte[] message = new byte[255];
DatagramPacket p = new DatagramPacket(message, message.length);
DatagramSocket s = new DatagramSocket(server_port);
s.receive(p);
hey = new String( message, 0 , p.getLength());
Log.d("MESSAGE: ", "Message is:" + hey);
s.close();
//codes for setting the Ultrasonic Sensor
if (hey.equals("Strainer is Empty")){
runOnUiThread(new Runnable() {
@Override
public void run() {
Empty.setAlpha((float) 0.8);
Full.setAlpha((float) 0.2);
SFull.setAlpha((float) 0.2);
AFull.setAlpha((float) 0.2);
}
});
}
if(hey.equals("Strainer is Full")){
runOnUiThread(new Runnable() {
@Override
public void run() {
Full.setAlpha((float) 0.8);
Empty.setAlpha((float)0.2);
SFull.setAlpha((float) 0.2);
AFull.setAlpha((float) 0.2);
}
});
}
问题是每当我回到我的主要活动并调用此活动时,错误似乎在数据报套接字上指出。我已阅读有关绑定地址但我不知道如何实现它
答案 0 :(得分:0)
当我尝试以这种方式实现时,我解决了这个问题
DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.setBroadcast(true);
s.bind(new InetSocketAddress(server_port));