簡體   English   中英

在Java套接字編程中需要幫助[服務器和客戶端]

[英]Need help in Java Socket Programming[server & client]

我使用Java套接字創建了一個名為server.java的Java服務器,該服務器從Android上的客戶端( client.java )接收字符串,對其進行修改並將修改后的字符串發送給客戶端(在我的情況下為Android應用)。

當我嘗試同時運行它們時,android應用程序成功將用戶輸入的字符串發送到服務器。 當服務器接收到字符串時會出現問題,有時服務器不提供任何輸出。 但是,如果客戶端關閉(或終止),則服務器終端輸出為:

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

readLine()在流的末尾(即,當對等方關閉連接時readLine()返回null。 您沒有檢測到這種情況:您將null視為數據。 當您獲得空值時,您需要終止讀取循環。

注意: print()readLine()不能引發UnknownHostException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM