Problems & Solutions
1、NetworkOnMainThreadException
不能直接在主界面线程中创建Socket。需要将其放在子线程中执行。
LogCat报错信息如下
FATAL EXCEPTION: main
Process: com.miui.hongbao, PID: 763
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.miui.hongbao/com.miui.hongbao.MainActivity}: android.os.NetworkOnMainThreadException
解决方案,将创建Socket、发送数据的代码放到子线程中执行。
public class NetClient extends AsyncTask<Void,Void,String> {
private Socket _sockClient;
private String _strIp;
private int _nPort;
private OutputStream _os;
public int initSocket(String Ip,int nPort) throws IOException {
_strIp=Ip;
_nPort=nPort;
return 1;
}
/**
*
* @param strSnd the str to send
* @return the length of send str
* @throws IOException
*/
public int sendData(String strSnd) throws IOException,NullPointerException {
_os=_sockClient.getOutputStream();
_os.write(strSnd.getBytes());
return strSnd.length();
}
@Override
protected String doInBackground(Void... params) {
try {
_sockClient= new Socket(_strIp,_nPort);
_sockClient.setSoTimeout(5000);
sendData("hehe from android tcp client");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Acitivy中调用代码:
mNetClient=new NetClient();
try {
mNetClient.initSocket(mTcpServIp,mTcpPort);
} catch (IOException e) {
e.printStackTrace();
}
mNetClient.execute();
注意配置文件中添加网络控制的权限。
<!--允许应用程序完全使用网络-->
<uses-permission android:name="android.permission.INTERNET"/>
2、connect failed: ETIMEDOUT
由于本人是在win10 64位下开发此项目,将防火墙关闭即可。