我一直在尝试让 SocketServer 在我的手机上工作。我最近升级到 ICS,所以现在我需要在一个单独的线程中做我的网络工作,这是我不习惯的。我已经编写了一些代码,但是一旦我尝试连接到套接字,应用程序就会崩溃。
当切换开关切换时,我启动 serverSocket:
final Switch connectionSwitch = (Switch) findViewById(R.id.connectionSwitch);
connectionSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
new Thread(){
public void run() {
try {
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
outToServer = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while(connectionSwitch.isChecked()) {
myPacket[0] = (byte) 0xAA;
myPacket[1] = (byte) 0x01;
myPacket[2] = (byte) (fanFrontSpeed/256);
myPacket[3] = (byte) (fanFrontSpeed%256);
myPacket[4] = (byte) (fanLeftSpeed/256);
myPacket[5] = (byte) (fanLeftSpeed%256);
myPacket[6] = (byte) (fanRightSpeed/256);
myPacket[7] = (byte) (fanRightSpeed%256);
try {
outToServer.write(myPacket,0,8);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}.start();
}
}
});
我得到的错误是:
FATAL EXCEPTION: Thread-4487
java.lang.NullPointerException