在android中拒绝第二次连接到服务器套接字

时间:2015-08-27 04:28:13

标签: android sockets

我有一个客户端/服务器套接字程序,用于通过直接WIFI连接工作的android。它包括客户端和服务器电话之间的多个请求和响应。我的代码第一次完美运行,但在第二次客户端获得"连接被拒绝"和服务器"套接字关闭"错误信息。第三次它再次工作,并在第四次提出错误和.... 有人可以帮我解决这个问题吗? 这是服务器代码:

new Thread(){
            public void run(){                
            ServerSocket welcomeSocket = null;
                try {
                    //Create a socket and listen to that
                    try {
                        if(welcomeSocket == null)
                            welcomeSocket = new ServerSocket(COMMUNICATION_PORT);
                    }catch(Exception qwe){
                        Log.d("Info", "qwe:" + qwe.getMessage());
                    }
                    int i = 0;
                    while (i == 0) {

                        try {
                            //Waiting for client connection
                            socket = welcomeSocket.accept();
                        }catch(Exception qwe2){
                            Log.d("Info", "qwe2:" + qwe2.getMessage());
                        }
                        //i++;

                        new Thread(){
                            public void run(){
                                try {
                                    InputStream is;
                                    DataInputStream dIn;
                                    OutputStream os;
                                    DataOutputStream dOut;
                                    //socket.setSoTimeout(SOCKET_TIMEOUT);
                                    log("Connection accepted");
                                    //Create an input stream for receiving data from server
                                    is = socket.getInputStream();
                                    dIn = new DataInputStream(is);
                                    //Get an output stream for sending data to server phone
                                    os = socket.getOutputStream();
                                    dOut = new DataOutputStream(os);

                                    boolean done = false;
                                    byte messageType;
                                    String message;
                                    int serverReplyType = 0;
                                    String serverReply = "NOP";

                                    while (!done) {
                                        messageType = dIn.readByte();
                                        message = dIn.readUTF();

                                        Log.d("Info", "Received: " + messageType);
                                        Log.d("Info", "Received: " + message);

                                        switch (messageType) {
                                            //----------------------------------------
                                            //Comparing Job ID and Location ID of client phone and server phone
                                            case JOB_ID_CHECK_REQ:
                                                String[] tokens = message.split("#");
                                                serverReplyType = JOB_ID_CHECK_RESP;
                                                if (Integer.parseInt(tokens[0]) == currentJob.getJobId() && Integer.parseInt(tokens[1]) == currentJob.getJobLocationId()) {
                                                    serverReply = "ACCEPTED";
                                                    log("Syncing data verified");
                                                } else {
                                                    serverReply = "ID MISMATCH";
                                                    done = true;
                                                    log("It is not possible to sync none equal Jobs.");
                                                    log("Please select same Job in both phone.");
                                                }
                                                break;
                                            //----------------------------------------
                                            //Generating JSON string including Racks data
                                            case RACK_LIST_REQ:
                                                log("Sending Racks' data");
                                                serverReplyType = RACK_LIST_RESP;
                                                serverReply = racks.size() > 0 ? (new Gson()).toJson(racks) : "NOP";
                                                break;
                                            //----------------------------------------
                                            //Inserting new Racks to local Db
                                            case NEW_RACK_FOR_INSERT:
                                                log("Receiving new Racks' data for insert");
                                                if (!message.equals("NOP")) {
                                                    List<Rack> diffRacks = new Gson().fromJson(message, new TypeToken<List<Rack>>() {
                                                    }.getType());
                                                    rackDataSource rds = new rackDataSource(CrossPhoneSync.this);
                                                    rds.open();
                                                    rds.crossPhoneSync_InsertDiff(diffRacks);
                                                    rds.close();
                                                }
                                                serverReplyType = DONE;
                                                serverReply = "NOP";
                                                done = true;
                                                break;
                                            //----------------------------------------
                                            case DONE:
                                                done = true;
                                                log("Done");
                                                break;
                                        }

                                        Log.d("Info", "Send: " + serverReplyType);
                                        Log.d("Info", "Send: " + serverReply);
                                        dOut.writeByte(serverReplyType);
                                        dOut.writeUTF(serverReply);
                                        dOut.flush();
                                    }
                                    log("Operation completed!");
                                } catch (Exception e) {
                                    log("Error: " + e.getMessage());
                                    Log.d("Info", "ServerPhoneError:" + e.getMessage());
                                    e.printStackTrace();
                                } finally {
                                    //Close stream and socket
                                    //closeSocket(true);
                                    Disconnect(null);
                                }
                                log("Done!");
                            }
                        }.start();
                    }
                }catch(Exception qw){
                    Log.d("Info", "Eq1:" + qw.getMessage());
                }finally {
                    try {
                        if (welcomeSocket != null) {
                            welcomeSocket.close();
                        }
                    }catch (Exception e) {
                        Log.d("Info", "Close_ServerSocket@: " + e.getMessage());
                    }
                }
            }
        }.start();

和客户端代码:

Socket socket2 = null;
                try {
                    InputStream is;
                    DataInputStream dIn;
                    OutputStream os;
                    DataOutputStream dOut;
                    //Create a socket for connecting to server phone
                    socket2 = new Socket(host, COMMUNICATION_PORT);
                    //socket.setSoTimeout(SOCKET_TIMEOUT);
                    //Get an output stream for sending data to server phone
                    os = socket2.getOutputStream();
                    dOut = new DataOutputStream(os);
                    //Create an input stream for receiving data from server
                    is = socket2.getInputStream();
                    dIn = new DataInputStream(is);

                    //Send first message
                    log("Sending verification data...");
                    int clientMessageType = JOB_ID_CHECK_REQ;
                    String clientMessageToSend = currentJob.getJobId() + "#" + currentJob.getJobLocationId();
                    dOut.writeByte(clientMessageType);
                    dOut.writeUTF(clientMessageToSend);
                    dOut.flush();

                    byte messageType;
                    String message;
                    boolean done = false;

                    while(!done) {
                        messageType = dIn.readByte();
                        message = dIn.readUTF();

                        Log.d("Info", "" + messageType);
                        Log.d("Info", message);

                        switch(messageType)
                        {
                            //----------------------------------------
                            //Sending current Job ID and Location ID to server phone for equality checking
                            case JOB_ID_CHECK_RESP:
                                if(message.equals("ACCEPTED")){
                                    log("Data verified");
                                    clientMessageType = RACK_LIST_REQ;
                                    clientMessageToSend = "NOP";
                                    log("Requesting for other phone's Racks data");
                                }else{
                                    done = true;
                                    log("It is not possible to sync none equal Jobs.");
                                    log("Please select same Job in both phone.");
                                }
                                break;
                            //----------------------------------------
                            //Comparing...
                            case RACK_LIST_RESP:
                                log("Comparing Racks' data of two phones");
                                List<Rack> serverPhoneRacks;
                                if(!message.equals("NOP"))
                                    serverPhoneRacks = new Gson().fromJson(message, new TypeToken<List<Rack>>() { }.getType());
                                else
                                    serverPhoneRacks = new ArrayList<>();
                                rackDataSource rds = new rackDataSource(CrossPhoneSync.this);
                                rds.open();
                                List<Rack> diffRacks = rds.crossPhoneSync_Compare(racks,serverPhoneRacks);
                                rds.close();

                                clientMessageType = NEW_RACK_FOR_INSERT;
                                clientMessageToSend = diffRacks == null ? "NOP" : (new Gson()).toJson(diffRacks);
                                log("Sending new Racks' data for inserting on the other phone");

                                break;
                            //----------------------------------------
                            case DONE:
                                done = true;
                                log("Done!");
                                break;
                        }

                        if(!done) {
                            dOut.writeByte(clientMessageType);
                            dOut.writeUTF(clientMessageToSend);
                            dOut.flush();
                        }
                    }
                    log("Operation completed!");
                }catch (Exception e) {
                    log("Error:" + e.getMessage());
                    e.printStackTrace();
                    Log.d("Info", " ClientPhoneError:" + e.getMessage());
                }finally {
                    //Close stream and socket
                    //closeSocket(false);
                    try {
                        if (socket2 != null) {
                            //socket.shutdownInput();
                            //socket.shutdownOutput();
                            socket2.close();
                        }
                    }catch (Exception e) {
                        Log.d("Info", "Close_Socket_Error5: " + e.getMessage());
                    }
                }
                log("Finished!");

0 个答案:

没有答案