简体   繁体   English

使用Android连接到本地服务器

[英]Connecting to a local server with Android

I state that I am not a newcomer to Android programming. 我声明自己不是Android编程的新手。

I can not connect to a server, the code I get this error: Required java.net.Socket found java.lang.Object 我无法连接到服务器,收到此错误的代码:找到java.lang.Object所需的java.net.Socket

This is the code so you can figure out what to do: 这是代码,因此您可以弄清楚该怎么做:

Then I press the button for the connection: 然后,我按下用于连接的按钮:

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();
}

By agreeing to launch the class SincTask : 通过同意启动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) {
            }
        }
    }

In Sink Task starts the method that handles the data received: SendCmd 在“接收器任务”中,启动处理接收到的数据的方法: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;

} }

Inside the method SendCmd method is called Connect To Server connecting to the server: 在方法SendCmd方法内部称为连接到服务器的连接到服务器:

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;
}

Use two classes: network and result generic result 使用两类:网络和结果通用结果

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;
    }
}

What's wrong? 怎么了? Or what is missing? 还是缺少什​​么?

Class TLVParser: 类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;
    }
}

**This is my LogCat : ** **这是我的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)

Your problem is at compile time and has nothing to do with servers or trying to connect to a server. 您的问题出在编译时,与服务器或尝试连接到服务器无关。 The only thing you had to post to reproduce your error is 您必须发布以重现错误的唯一内容是

public class genericresult extends fresul {
public Object Dati;

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

And then the statements: 然后声明:

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

Socket nsocket = r.Dati;

That would give you your error message Required java.net.Socket found java.lang.Object . 那将给您您的错误消息Required java.net.Socket found java.lang.Object

So Dati is not a Socket instance. 因此,Dati不是Socket实例。

Something else: 其他:

       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";
        }

It makes no sense to make a loop to try that five times. 循环尝试五次是没有意义的。 One time would be enough. 一次就足够了。 Then set a longer timeout. 然后设置更长的超时时间。

Moreover if the first try times out you already set a result value and an error message value which you do not remove or change when the second connect goes ok. 此外,如果第一次尝试超时,则您已经设置了结果值和错误消息值,当第二次连接正常时,您不会删除或更改该消息值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM