全双工服务器套接字实现,单独的读写线程?

发布于 2024-12-15 23:33:08 字数 4918 浏览 1 评论 0原文

我想在同一个服务器套接字(java应用程序)上读取和写入(从服务器到客户端随机)。我的客户端到服务器的写入和读取在循环中工作得很好。在服务器上正确写入响应。

但是如果我尝试在服务器上随机写入一些命令。我没有解决方案,首先我的问题是:

  1. 服务器端是否可以在同一套接字上向客户端 ramonly 写入命令?
  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... ");
    }

I want to read and write(randomly from server to client) on same server socket (java application). My client to server write and read work fine in a loop. At server with response write properly.

But if i am trying to write at server randomly some command. i do not have solution, first of all my question is :

  1. is it possible at server side to write command to client ramdonly on same socket?
  2. if possible, any suggestion or pointer how to do it?
  3. please give me some pointer where I can read the material about this scenario ?

thanks in advance.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天涯沦落人 2024-12-22 23:33:08

所以,我修好了它。我只需要维护两个不同的线程。
1)阅读。
2)写。

在上面的代码中,我刚刚又启动了一个用于 write 的线程。

将代码插入上述代码的 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);

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

然后在read的wile循环中启动线程。
使用以下代码进行检查。

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

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

谢谢大家回答我的问题。

So , I fixed it . I just need to maintain two different thread.
1) read.
2)write.

In the above code i just started one more thread for write .

insert the code in Run function of above code.

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

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

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

Then Start the thread in the wile loop of read.
with the following code with a check.

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

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

Thanks everyone, who respond my question..

べ繥欢鉨o。 2024-12-22 23:33:08

是的,可以将服务器或客户端上的多个线程的数据写入现有套接字。但是,您必须确保请求不会重叠,并且接收方实际上知道谁写了什么。

如果您使用基于行的协议,您可以将每条消息定义为一行。在这种情况下,您应该以一种方式同步多个线程,即在任何给定时刻只有一个线程写入该行的部分内容。

您的代码有点太大,无法理解您的问题所在,抱歉。

也许这个教程有帮助?有很多:

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

Yes it is possible to write data from multiple threads on a server or on a client to an existing socket. However you have to make sure the requests do not overlap, and the receiving side actually knows what is written from who.

If you use a line based protocol you can define each message is a single line. In that case you should synchronize multiple threads in a way that only one is writing parts of that line at any given moment.

Your code is a bit too big to understand where your problem is, sorry.

Maybe this tutorial helps? There are quite many out there:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文