在Java Socket Programming中需要帮助[server&客户]

时间:2016-12-30 08:10:30

标签: java android sockets

我使用java套接字创建了一个名为server.java的Java服务器,它接受来自Android上客户端(client.java)的字符串,修改它并将修改后的字符串发送到客户端[在我的情况下]是一个Android应用程序]。

当我尝试同时运行它们时,没有任何错误,android app成功地将用户输入的字符串发送到服务器。当服务器收到字符串时会出现问题,有时服务器不提供任何输出。但是如果客户端关闭(或被杀死),则服务器终端输出为:

 message received from client is: null
 request: Message sent to the client : i received message:null
 message received from client is: null
 request: Message sent to the client : i received message:null
 message received from client is: null
 request: Message sent to the client : i received message:null
 message received from client is: null
 request: Message sent to the client : i received message:null
 message received from client is: null
 request: Message sent to the client : i received message:null

以下是在桌面计算机上运行的Server.java的代码:

public class Server {
    static Socket socket;
    static PrintWriter out;
    static BufferedReader  in;
    static int port = 9999;

    public static void main(String[] args) { 

        String query="blank", returnMessage="Server malfunctioning!";

        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Server Started and listening to the port "+port);
            socket = serverSocket.accept();
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            while(true) {
                try {
                    query=in.readLine();
                    System.out.println("message received from client is: "+query);
                    //Processing the query.
                    returnMessage="i received message:"+query;

                    //Sending the response back to the client.
                    out.print(returnMessage);
                    System.out.println("request: Message sent to the client : " + returnMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    out.flush();
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch(Exception e) {
                System.out.println(e);
            }
        }
    }
}

此处ServerConnect.java扩展了AsyncTask

public class ServerConnect extends AsyncTask<Object, Object, Void> {
    String TAG="Server";  
    String message="empty response";
    String ip="EMPTY QUERY";
    WebView wb;
    TextToSpeech tts;
    String host = "192.168.2.3";
    int port = 9999;
    PrintWriter out;
    BufferedReader  in;
    Socket  socket;

    ServerConnect(String inp, WebView wbb, TextToSpeech ts) {
       ip=inp;
       this.wb=wbb;
       tts=ts;
    }

    @Override
    protected Void doInBackground(Object... voids) {
        Log.d(TAG, "ip value "+ip);
        try {
            // InetAddress address = InetAddress.getByName(host);
            socket = new Socket(host, port);
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            try {
                //Send the message to the server
                out.print(ip);
                //out.flush();
                Log.d(TAG, "request: Message sent to the server : " + ip);
                message = in.readLine();
                Log.d(TAG, "doInBackground: message" + message);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                message = "UnknownHostException: " + e.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                message = "My Brain is not working! Reason is: "+e;
            } finally {
                in.close();
                out.flush();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Log.d(TAG, "doInBackground: finally block");

            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    protected void onPostExecute(Void result) {
        // wb.getSettings().setJavaScriptEnabled(true);
        if(message!=null) {
            wb.loadDataWithBaseURL(null, message, "text/html", "utf-8", null);
            tts.speak(stripHtml(message), TextToSpeech.QUEUE_FLUSH, null, null);
            if (!(pullLinks(stripHtml(message)).equals(""))) {
                wb.setWebViewClient(new WebViewClient());
                wb.setWebChromeClient(new WebChromeClient() {});
                wb.loadUrl(pullLinks(message));
                //ip.setText("");
                super.onPostExecute(result);
            }
        } else {
            wb.loadDataWithBaseURL(null, "Message is null!", "text/html", "utf-8", null);
            tts.speak("Message is null!", TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }

    public String stripHtml(String html) {
        return Html.fromHtml(html).toString(); 
    }

    private String pullLinks(String text) {
        String links="";

        String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);

        while(m.find()) {
            String urlStr = m.group();
            if (urlStr.startsWith("(") && urlStr.endsWith(")"))
                urlStr = urlStr.substring(1, urlStr.length() - 1);

            links=urlStr;
        }

        return links;
    }
}

1 个答案:

答案 0 :(得分:0)

readLine()在流的末尾返回null,即当对等方关闭连接时。您没有检测到这种情况:您将null视为数据。当你得到null时,你需要终止读循环。

UnknownHostExceptionprint()无法抛出NB readLine()