使用Android连接到本地服务器

时间:2016-01-11 10:06:06

标签: android mysql sockets server

我声明我不是Android编程的新手。

我无法连接到服务器,代码我收到此错误: 需要java.net.Socket找到java.lang.Object

这是代码,因此您可以找出要做的事情:

然后我按下连接按钮:

private void RegistraTerminale() {
    new AlertDialogWrapper.Builder(this)
            .setTitle(R.string.configurazioni_dialog_registra_titolo)
            .setMessage(R.string.configurazioni_dialog_registra_messaggio)
            .setPositiveButton(R.string.configurazioni_dialog_registra_si, new DialogInterface.OnClickListener() {
                @Override
            public void onClick(DialogInterface dialog, int which) {
                    pd = new MaterialDialog.Builder(context)
                            .title(R.string.configurazioni_progress_dialog_registra_titolo)
                            .content(R.string.configurazioni_progress_dialog_registra_content)
                            .progress(true, 0)
                            .show();
                    new SincTask().execute(new String[]{_androidId});
                }
            })
            .setNegativeButton(R.string.configurazioni_dialog_registra_no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .show();
}

同意启动SincTask类:

private class SincTask extends AsyncTask<String, String, genericresult> {
        private SincTask() {
        }

        protected genericresult doInBackground(String... params) {
            genericresult Ret = new genericresult(0, null, BuildConfig.FLAVOR);
            try {
                String datiXml = params[0].replace('[', ' ').replace(']', ' ').trim();
                String ipServer = BuildConfig.FLAVOR;
                int PortaServer = 0;
                Cursor c = ConnessioneAlServer.getAllServer(db);
                while (c.moveToNext()) {
                    ipServer = c.getString(0);
                    PortaServer = c.getInt(1);
                }
                if (ipServer == BuildConfig.FLAVOR || PortaServer == 0) {
                    ipServer = "192.168.1.2";
                    PortaServer = 4444;
                }
                publishProgress(new String[]{"Comunicazione con il server..."});
                networkresult r = SendCmd(datiXml, ipServer, PortaServer);
                Ret.result = r.result;
                if (r.result != 0) {
                    Ret.errMesg = r.errMesg;
                }
            } catch (Exception ex) {
                Log.e("StartDbSincTask:", ex.getMessage());
            }
            return Ret;
        }

        protected void onProgressUpdate(String... values) {
            try {
                pd.setContent(values[0]);
            } catch (Exception ex) {
                Log.e("onProgressUpdate:", ex.getMessage());
            }
        }

        protected void onPostExecute(genericresult result) {
            try {
                if (result.result != 0) {
                    crea_snackbar("result !=0 " + result.errMesg, true);
                } else if (result.errMesg.compareTo(BuildConfig.FLAVOR) != 0) {
                    crea_snackbar("Errore  " + result.errMesg, true);
                } else {
                    crea_snackbar("il terminale è stato correttamente registrato.", true);
                }
                //pd.dismiss();
            } catch (Exception e) {
            }
        }
    }

在Sink Task中启动处理收到数据的方法:SendCmd

private networkresult SendCmd(String datiDaInviare, String Sever, int PortaTCP) {
networkresult Ret = new networkresult(0, BuildConfig.FLAVOR, BuildConfig.FLAVOR);
try {
    if (datiDaInviare == BuildConfig.FLAVOR) {
        Ret.result = -1;
        Ret.errMesg = "Nessun ID terminale rilevato.";
        Log.e("ERRORE", "Nesun ID terminale rilevato SendCmd");
    } else {
        genericresult r = new genericresult(0,null,BuildConfig.FLAVOR);
        Socket nsocket = null;
        genericresult novarum_risto_vrordina_genericresult = new genericresult(0, null, BuildConfig.FLAVOR);
        int index = 0;
        while (index < 4) {
            r = CollegaAlServer(Sever, PortaTCP, 1000);
            Log.e("SendCmd","é stato appena avviato il metodo CollegaAlServer");
            Log.e("r result", ""+r.result);
            if (r.result == 0) {
                int length;
                nsocket = (Socket)r.Dati;
                SocketAddress sockaddr = new InetSocketAddress(Sever, PortaTCP);
                nsocket.connect(sockaddr, 1000);
                Log.e("SendCmd","Avviata la connessione dentro all'if");
                nsocket.setSoTimeout(5000);
                InputStream nis = nsocket.getInputStream();
                OutputStream nos = nsocket.getOutputStream();
                ArrayList<Byte> dati = new ArrayList();
                dati.add(Byte.valueOf((byte) 95));
                byte[] len = TLVParser.intToByteArray(datiDaInviare.length());
                TLVParser.reverse(len);
                int i = 0;
                while (true) {
                    length = len.length;
                    if (i >= 0) {
                        break;
                    }
                    dati.add(Byte.valueOf(len[i]));
                    i++;
                }
                byte[] contenuto = datiDaInviare.getBytes("UTF-8");
                i = 0;
                while (true) {
                    length = contenuto.length;
                    if (i >= 0) {
                        break;
                    }
                    dati.add(Byte.valueOf(contenuto[i]));
                    i++;
                }
                byte[] datatosend = new byte[dati.size()];
                for (i = 0; i < dati.size(); i++) {
                    datatosend[i] = ((Byte) dati.get(i)).byteValue();
                }
                nos.write(datatosend);
                byte[] ret = TLVParser.readTLV(nis, 95);
                if (ret == null) {
                    Ret.result = -1;
                    Ret.errMesg = "Errore comunicazione con il server";
                    Log.e("ERRORE", "ERRORE Comunicazione con il server SendCmd");
                } else {
                    Ret.Dati = new String(ret);
                    if (Ret.Dati.compareTo("OK") != 0) {
                        Ret.result = -1;
                        Ret.errMesg = Ret.Dati;
                    }
                }
                if (nsocket != null) {
                    nsocket.close();
                }
                if (r.result != 0) {
                    Ret.result = -1;
                    Ret.errMesg = "Errore collegamento 2 con il server";
                    Log.e("ERRORE","Errore collegamento con il server 2 SendCmd");
                }
            } else {
                index++;
            }
        }
        if (nsocket != null) {
            nsocket.close();
        }
        if (r.result != 0) {
            Ret.result = -1;
            Ret.errMesg = "Errore collegamento 3 con il server";
            Log.e("ERRORE", "Errore collegamento con il server 3 SendCmd");
        }
    }
} catch (Exception e) {
    e.printStackTrace();
    Ret.result = -1;
    Ret.errMesg = e.getMessage();
}
return Ret;

}

方法内部SendCmd方法称为Connect To Server连接到服务器:

private genericresult CollegaAlServer(String Sever, int PortaTCP, int timeout) {
    genericresult ret = new genericresult(0, null, BuildConfig.FLAVOR);
    try {
        SocketAddress sockaddr = new InetSocketAddress(Sever, PortaTCP);
        Socket nsocket = new Socket();
        for (int index = 0; index < 5; index++) {
            nsocket.connect(sockaddr, timeout);
            if (nsocket.isConnected()) {
                ret.Dati = nsocket;
                Log.e("CollegaAlServer","Il socket si è connesso");
                break;
            }
            ret.result = -1;
            ret.errMesg = "Errore collegamento con il server";
            Log.e("ERRORE","Errore collegamento con il serer, private CollgaAlServer");
        }
    } catch (Exception e) {
        e.printStackTrace();
        ret.result = -1;
        ret.errMesg = e.getMessage();
    }
    return ret;
}

使用两个类:网络和结果通用结果

public class genericresult extends fresul {
    public Object Dati;

    public genericresult(int ret, Object dati, String errormsg) {
        super(ret, errormsg);
        this.Dati = dati;
    }
}

public class networkresult extends fresul {
    public String Dati;

    public networkresult(int ret, String dati, String errormsg) {
        super(ret, errormsg);
        this.Dati = dati;
    }
}

出了什么问题?或者缺少什么?

Class TLVParser:

public class TLVParser {
    public static String toUTF8(String isoString) {
        String utf8String = isoString;
        if (isoString == null || isoString.equals(BuildConfig.FLAVOR)) {
            return utf8String;
        }
        try {
            return new String(isoString.getBytes(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("UnsupportedEncodingException is: " + e.getMessage());
            return isoString;
        }
    }

    public static final byte[] intToByteArray(int value) {
        return new byte[]{(byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value};
    }

    public static void reverse(byte[] array) {
        if (array != null) {
            int j = array.length - 1;
            for (int i = 0; j > i; i++) {
                byte tmp = array[j];
                array[j] = array[i];
                array[i] = tmp;
                j--;
            }
        }
    }

    public static byte[] readTLV(InputStream tlv, int tag) {
        if (tlv == null) {
            throw new IllegalArgumentException("Invalid TLV");
        }
        byte[] vals = null;
        try {
            int c = tlv.read();
            if (c != 1 && c == tag) {
                ByteBuffer bb = ByteBuffer.allocate(4);
                c = tlv.read();
                if (c != -1) {
                    bb.put((byte) c);
                }
                c = tlv.read();
                if (c != -1) {
                    bb.put((byte) c);
                }
                c = tlv.read();
                if (c != -1) {
                    bb.put((byte) c);
                }
                c = tlv.read();
                if (c != -1) {
                    bb.put((byte) c);
                }
                int Len = bb.getInt(0);
                vals = new byte[Len];
                int Residuo = Len;
                int MaxRead = AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT;
                if (AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT > Residuo) {
                    MaxRead = Residuo;
                }
                int offSet = 0;
                byte[] bytes = new byte[Len];
                while (Residuo > 0) {
                    while (true) {
                        int len = tlv.read(bytes, 0, MaxRead);
                        if (len > 0) {
                            System.arraycopy(bytes, 0, vals, offSet, len);
                            offSet += len;
                            Residuo -= len;
                            if (MaxRead > Residuo) {
                                MaxRead = Residuo;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            String errmsg = e.getMessage();
            e.printStackTrace();
        }
        return vals;
    }

    public static byte[][] readTLV(String tlvHexString, int tag) throws Throwable {
        return readTLV(hexStringToByteArray(tlvHexString), tag);
    }

    public static byte[][] readTLV(byte[] tlv, int tag) throws Throwable {
        Throwable th;
        if (tlv == null || tlv.length < 1) {
            throw new IllegalArgumentException("Invalid TLV");
        }
        ArrayList al = new ArrayList();
        ByteArrayInputStream is = null;
        try {
            ByteArrayInputStream is2 = new ByteArrayInputStream(tlv);
            while (true) {
                try {
                    int c = is2.read();
                    if (c == -1) {
                        break;
                    } else if (c == tag) {
                        ByteBuffer bb = ByteBuffer.allocate(4);
                        c = is2.read();
                        if (c != -1) {
                            bb.put((byte) c);
                        }
                        c = is2.read();
                        if (c != -1) {
                            bb.put((byte) c);
                        }
                        c = is2.read();
                        if (c != -1) {
                            bb.put((byte) c);
                        }
                        c = is2.read();
                        if (c != -1) {
                            bb.put((byte) c);
                        }
                        int Len = bb.getInt(0);
                        byte[] value = new byte[Len];
                        is2.read(value, 0, Len);
                        al.add(value);
                    }
                } catch (Throwable th2) {
                    th = th2;
                    is = is2;
                }
            }
            if (is2 != null) {
                try {
                    is2.close();
                } catch (IOException e) {
                }
            }
            byte[][] vals = new byte[al.size()][];
            al.toArray(vals);
            return vals;
        } catch (Throwable th3) {
            th = th3;
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e2) {
                }
            }
            throw th;
        }
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[(len / 2)];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            value += (b[i + offset] & MotionEventCompat.ACTION_MASK) << ((3 - i) * 8);
        }
        return value;
    }
}

**这是我的LogCat:**

01-13 10:37:09.738 14592-17524/com.edsoft.vrcomande2 W/System.err: java.net.SocketException: Already connected
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at java.net.Socket.connect(Socket.java:813)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at com.edsoft.vrcomande2.ConfigurazioniActivity.SendCmd(ConfigurazioniActivity.java:351)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at com.edsoft.vrcomande2.ConfigurazioniActivity.access$600(ConfigurazioniActivity.java:48)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at com.edsoft.vrcomande2.ConfigurazioniActivity$SincTask.doInBackground(ConfigurazioniActivity.java:264)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at com.edsoft.vrcomande2.ConfigurazioniActivity$SincTask.doInBackground(ConfigurazioniActivity.java:240)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-13 10:37:09.743 14592-17524/com.edsoft.vrcomande2 W/System.err:     at java.lang.Thread.run(Thread.java:841)

1 个答案:

答案 0 :(得分:0)

您的问题是在编译时,与服务器无关或尝试连接到服务器。您要发布以重现错误的唯一方法是

public class genericresult extends fresul {
public Object Dati;

public genericresult(int ret, Object dati, String errormsg) {
    super(ret, errormsg);
    this.Dati = dati;
}
}

然后是陈述:

genericresult r = new genericresult(0, null, BuildConfig.FLAVOR);

Socket nsocket = r.Dati;

这会向您显示错误消息Required java.net.Socket found java.lang.Object

所以Dati不是Socket实例。

其他东西:

       for (int index = 0; index < 5; index++) {
            nsocket.connect(sockaddr, timeout);
            if (nsocket.isConnected()) {
                ret.Dati = nsocket;
                break;
            }
            ret.result = -1;
            ret.errMesg = "Errore collegamento con il server";
        }

循环尝试五次是没有意义的。一次就足够了。然后设置更长的超时。

此外,如果第一次尝试超时,您已经设置了结果值和错误消息值,当第二次连接正常时,您不会删除或更改错误消息值。