我有一个用Thread扩展的线程类,我试图在其他类中创建该类的对象并从那里启动线程,当按下按钮时将创建线程但是app只运行正常曾经,我创建线程的主要类是:
broadcastobject=new broadcast(messages);
broadcastobject.start();
我的主题类是:
public class broadcast extends Thread{
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public broadcast(String msg){
str=msg;
}
@Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我的日志猫是:
09-02 15:46:47.603: W/System.err(1348): java.net.BindException: bind failed: EADDRINUSE (Address already in use)
09-02 15:46:47.613: W/System.err(1348): at libcore.io.IoBridge.bind(IoBridge.java:89)
09-02 15:46:47.613: W/System.err(1348): at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:68)
09-02 15:46:47.643: W/System.err(1348): at java.net.DatagramSocket.createSocket(DatagramSocket.java:133)
09-02 15:46:47.703: W/System.err(1348): at java.net.DatagramSocket.<init>(DatagramSocket.java:78)
09-02 15:46:47.703: W/System.err(1348): at soft.b.peopleassist.broadcast.run(broadcast.java:65)
09-02 15:46:47.703: W/System.err(1348): Caused by: libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in use)
09-02 15:46:47.703: W/System.err(1348): at libcore.io.Posix.bind(Native Method)
09-02 15:46:47.772: W/System.err(1348): at libcore.io.ForwardingOs.bind(ForwardingOs.java:39)
09-02 15:46:47.772: W/System.err(1348): at libcore.io.IoBridge.bind(IoBridge.java:87)
09-02 15:46:47.772: W/System.err(1348): ... 4 more
09-02 15:46:47.793: W/dalvikvm(1348): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
09-02 15:46:47.823: E/AndroidRuntime(1348): FATAL EXCEPTION: Thread-79
09-02 15:46:47.823: E/AndroidRuntime(1348): java.lang.NullPointerException
09-02 15:46:47.823: E/AndroidRuntime(1348): at soft.b.peopleassist.broadcast.run(broadcast.java:90)
09-02 15:47:21.832: I/Process(1348): Sending signal. PID: 1348 SIG: 9
答案 0 :(得分:0)
您正在尝试在已使用的端口上绑定套接字。 您需要在绑定新套接字之前关闭绑定套接字。
你的应用程序下的Linux系统可能需要一些时间才能注意到,绑定的套接字已经消失,如果你只是让你的应用程序崩溃或忘记在Socket.close()
中拨打onDestroy()
或在你的适当的任何地方情况下。