我目前正在开发一个需要Android应用程序连接到我创建的java服务器的项目。问题是套接字没有初始化。我已将权限添加到AndroidManifest.xml文件
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
我的应用代码如下:
按钮触发:
View.OnClickListener btnDownloadListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
//Implement download code
try{
new ConnectionManager().execute("10.90.181.91" , "21002");
}catch(Throwable t){
}
}
};
ConnectionManager背景功能:
protected String doInBackground(String... args) {
try{
Log.i("Test", "background thread started");
int port = Integer.parseInt(args[1]);
InetAddress serverAddr = InetAddress.getByName(args[0]);
Socket connSock = new Socket(serverAddr, port);
Log.i("Test", "Created Socket");
}catch(Throwable t){
}
return "";
}
日志输出“background Thread Started”,但从不输出“Created Socket”
服务器代码如下: 主要方法
try{
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(21002);
} catch (IOException e) {
System.err.println("Could not listen on port: 21002");
}
int count = 0;
while(listeningSocket){
try{
Socket clientSocket = serverSocket.accept();
new ServerThread(clientSocket).start();
}catch(Throwable t){
}
}
System.out.println("You should not be here");
serverSocket.close();
}catch(Throwable t){
}
ServerThread
public class ServerThread extends Thread {
private Socket socket = null;
private String s;
private InputStream in;
private OutputStream out;
BufferedReader is;
BufferedWriter os;
public ServerThread(Socket s) {
socket = s;
System.out.println("Thread started: " + socket.getInetAddress());
try{
in = socket.getInputStream();
out = socket.getOutputStream();
out.flush();
is = new BufferedReader(new InputStreamReader(in));
os = new BufferedWriter(new OutputStreamWriter(out));
}catch(Throwable t){
t.printStackTrace();
}
}
public void run() {
System.out.println("Thread is running");
String dataType = "";
Boolean awaitingTransfer = false;
try {
while(true){
if(in.available() > 0 && !awaitingTransfer){
dataType = is.readLine();
System.out.println(dataType);
}
if(in.available() > 0 && awaitingTransfer){
try{
ArrayList<SpotCheck> tempList = new ArrayList<SpotCheck>();
while(in.available() > 0){
//tempList = (ArrayList<SpotCheck>) in.readObject();
}
ServerMain.manager.applyChanges(tempList);
awaitingTransfer = false;
}catch(Throwable t){
t.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
try {
in.close();
out.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
感谢您的帮助!
答案 0 :(得分:0)
作为一名业余编码员,我只是想问你,你能不能像你那样在doInBackground的“catch()”博客上添加祝酒词
catch(Exception e)
{
runOnUiThread(new Runnable(){
@Override
public void run(){
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
});
}
因此它可以更具体地显示您的问题,并且可能更容易处理。但我又不确定它是否有效,我的意思是在asynctask类中使用toast有点棘手。