1

同じサーバーソケット(Javaアプリケーション)で(サーバーからクライアントへランダムに)読み書きしたい。私のクライアントからサーバーへの書き込みと読み取りは、ループ内で正常に動作します。応答のあるサーバーで適切に書き込みます。

しかし、サーバーでランダムにコマンドを書き込もうとしている場合。私には解決策がありません。まず私の質問は次のとおりです。

  1. サーバー側で同じソケットのクライアント ramdonly にコマンドを書き込むことは可能ですか?
  2. 可能であれば、それを行う方法についての提案や指針はありますか?
  3. このシナリオに関する資料を読むことができる場所を教えてください。

前もって感謝します。

public class ContentServerSocket extends ServerSocket {
    private final static int PORT = 4444;

    protected static boolean XYZGONE = false;
    public static Content content;

    public ContentServerSocket(xyzService service) throws IOException {
        super(PORT);

        while (true) {

            Log.d(TAG, "Waiting for new request from client(content) ....");
            new HandleRequest(accept(), service).start();
        }
    }

    public static void xyzRunAway() {
        Log.d(TAG," Content Serv er 1 ");
        XYZGONE = true;
    }

}

class HandleRequest extends Thread {
    private final static String TAG = "ContentServerSocket:Thread for a request:";
    private Socket client;
    private xyzService service;

    private static  Context context;

    HandleRequest(Socket client, SuggestionService service) {
        this.client = client;
        this.service = service;
        context = xyzService.serviceContext();  
    }

    public void run() {
        while (true) {
            try {

                Log.d(TAG, " Step 1: client: Received request  MSG for Check...  ");
                PrintWriter out = new PrintWriter(client.getOutputStream(),
                        true);

                BufferedReader in = new BufferedReader(new InputStreamReader(
                        client.getInputStream(), "utf-8"));
                String request = "";
                String tmpLine = null;


                Log.d(TAG, " Step Xyz waiting data from the client ...  ");


                while ((tmpLine = in.readLine()) != null) {

                    if (tmpLine.length() > 0) {
                        request += tmpLine;
                        //if (tmpLine.toLowerCase().contains("</contentInfo>")) {
                        if (tmpLine.contains("</contentInfo>")) {
                            Log.d(TAG, " Server : broke because of </contentInfo>");
                            break;
                        }
                    } else {
                        Log.d(TAG, " Step NULL :   ");
                        request = "";
                    }

                } 



                Log.d("Robin", " Step 2: Actual request received from the client : : " + request);
                if (request.length() == 0) {
                    Log.d("Robin",
                            " client got 0 length request, thread stop!");
                    throw new Exception();

                }
                //XMLParser xmlParser = new XMLParser(new ByteArrayInputStream(
                //      request.getBytes("UTF-8")));

                Log.d(TAG, " Step 3 :   ");
                RequestParser readxmlrequest = new RequestParser(request);
                String requestType = readxmlrequest.parsingXmlRequestFromContent();
                Log.d(TAG, " Step 4  requestType :   " + requestType);


                //TODO : need to get the result and pas to the out.println..

                //String result = processXML(xmlParser);

                String result = responseToContentRequest(readxmlrequest,requestType);//null; //TODO need to complete.
                Log.d(TAG, " Step 5 result :   "+result);
                 (((((((((())))))))))";
                if (result != null && result.length() > 0) {

                    //oos.writeObject(result);
                    Log.d("Robin", " Writing response to socket ... ");
                    out.println(result + "\n");
                    out.flush();
                    Log.d("Robin", " Writing flush completed ");
                }

                if(ContentServerSocket.XYZGONE) {
                    Log.d(TAG," XYZGONE >>>>>>>> ");
                    ContentServerSocket.XYZGONE = false;
                    String tmp = "<ssr> OK Done .......</ssr>";
                    out.println(tmp + "\n");
                    Log.d("Content Server Socket ", "xyz:" + tmp);
                    out.flush();
                }

            } catch (IOException ioException) {
                Log.d("Robin", " IOException on socket listen: " + ioException);
            }
            catch (Exception e) {
                Log.d("Robin", " outer exception: " + e.toString());
                break;
            }

            finally {
                if (client == null || client.isClosed()
                        || !client.isConnected()) {
                    Log.d(" Robin ", " client is null");
                    break;
                }
            }
            //break;

            }
        Log.d("Robin", " thread stop... ");
    }
4

2 に答える 2

2

だから、私はそれを修正しました。私は2つの異なるスレッドを維持する必要があります。1) 読む。2)書く。

上記のコードでは、 write 用にもう 1 つのスレッドを開始しました。

上記のコードの Run 関数にコードを挿入します。

================================================== ==

Runnable r1 = new Runnable() {
    public void run() {
            try {
            while (true) {
                System.out.println("Hello, world!");
                if(ContentServerSocket.XYZGONE) {
                    Log.d(TAG," XYZGONEY >>>>>>>> ");
                    ContentServerSocket.XYZGONE = false;
                    String tmp = "<ssr> OK Done .......</ssr>";
                    out.println(tmp + "\n");
                    Log.d("Content Server Socket ", "XYZGONE :" + tmp);
                    out.flush();
                }
                Thread.sleep(1000L);
            }
        } catch (InterruptedException iex) {}
    }
};

Thread thr1 = new Thread(r1);

==================================

次に、読み取りのワイルループでスレッドを開始します。次のコードにチェックを付けます。

====================================

if(!thr1.isAlive())thr1.start();

私の質問に答えてくれた皆さん、ありがとう..

于 2011-11-16T11:36:30.263 に答える
0

はい、サーバーまたはクライアント上の複数のスレッドから既存のソケットにデータを書き込むことができます。ただし、リクエストが重複しないようにする必要があり、受信側は実際に誰から何が書き込まれたかを知っています。

行ベースのプロトコルを使用する場合は、各メッセージが1行であると定義できます。その場合、常に1つだけがその行の一部を書き込んでいるように、複数のスレッドを同期する必要があります。

コードが少し大きすぎて、問題がどこにあるのか理解できません。ごめんなさい。

たぶん、このチュートリアルは役に立ちますか?そこにはかなりたくさんあります:

http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html

于 2011-11-16T04:57:25.110 に答える