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

Java 全双工服务器套接字实现,独立读写线程?,java,sockets,jakarta-ee,client,serversocket,Java,Sockets,Jakarta Ee,Client,Serversocket,我想在同一个服务器套接字(java应用程序)上读写(从服务器到客户端随机进行)。我的客户端到服务器的写和读在循环中工作良好。在服务器上正确写入响应 但若我试图在服务器上随机编写一些命令。我没有解决办法,首先我的问题是: 服务器端是否可以在同一个套接字上向客户机ramdonly写入命令 如果可能的话,有什么建议或指示如何做吗 请给我一些指针,我可以在哪里阅读关于这个场景的材料 提前谢谢 public class ContentServerSocket extends ServerSocket {

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

但若我试图在服务器上随机编写一些命令。我没有解决办法,首先我的问题是:

  • 服务器端是否可以在同一个套接字上向客户机ramdonly写入命令
  • 如果可能的话,有什么建议或指示如何做吗
  • 请给我一些指针,我可以在哪里阅读关于这个场景的材料 提前谢谢

    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... ");
        }
    
    公共类ContentServerSocket扩展了ServerSocket{
    专用最终静态int端口=4444;
    受保护的静态布尔值XYZGONE=false;
    公共静态内容;
    公共ContentServerSocket(xyzService服务)引发IOException{
    超级(港口);
    while(true){
    Log.d(标记“等待来自客户端的新请求(内容)…”);
    新HandleRequest(accept(),service).start();
    }
    }
    公共静态void xyzRunAway(){
    Log.d(标签“内容服务器1”);
    XYZGONE=true;
    }
    }
    类HandleRequest扩展了线程{
    私有最终静态字符串TAG=“ContentServerSocket:请求线程:”;
    专用套接字客户端;
    专用XYZ服务;
    私有静态语境;
    HandlerRequest(套接字客户端、建议服务){
    this.client=client;
    服务=服务;
    context=xyzService.serviceContext();
    }
    公开募捐{
    while(true){
    试一试{
    Log.d(标记“步骤1:客户端:接收到检查请求消息…”);
    PrintWriter out=新的PrintWriter(client.getOutputStream(),
    正确的);
    BufferedReader in=新的BufferedReader(新的InputStreamReader(
    client.getInputStream(),“utf-8”);
    字符串请求=”;
    字符串tmpLine=null;
    Log.d(标记“步骤Xyz等待来自客户端的数据…”);
    而((tmpLine=in.readLine())!=null){
    如果(tmpLine.length()>0){
    请求+=tmpLine;
    //if(tmpLine.toLowerCase()包含(“”){
    if(tmpLine.contains(“”){
    Log.d(标记“服务器:因为”而损坏);
    打破
    }
    }否则{
    Log.d(标记“步骤空:”);
    请求=”;
    }
    } 
    Log.d(“Robin”,“步骤2:从客户端收到的实际请求::”+请求);
    if(request.length()==0){
    Log.d(“罗宾”,
    “客户端收到0长度请求,线程停止!”);
    抛出新异常();
    }
    //XMLParser XMLParser=new XMLParser(new ByteArrayInputStream(
    //请求.getBytes(“UTF-8”);
    Log.d(标记“步骤3:”);
    RequestParser readxmlrequest=新的RequestParser(请求);
    String requestType=readxmlrequest.parsingXmlRequestFromContent();
    Log.d(标签,“步骤4请求类型:”+requestType);
    //TODO:需要将结果和pas发送到out.println。。
    //字符串结果=processXML(xmlParser);
    字符串结果=responseToContentRequest(readxmlrequest,requestType);//null;//TODO需要完成。
    Log.d(标签,“步骤5结果:”+结果);
    (((((((((())))))))))";
    if(result!=null&&result.length()>0){
    //oos.writeObject(结果);
    Log.d(“Robin”,“将响应写入套接字…”);
    out.println(结果+“\n”);
    out.flush();
    Log.d(“Robin”,“写入刷新完成”);
    }
    if(ContentServerSocket.XYZGONE){
    Log.d(标记“XYZGONE>>>>>>”;
    ContentServerSocket.XYZGONE=false;
    字符串tmp=“确定完成……”;
    out.println(tmp+“\n”);
    Log.d(“内容服务器套接字”,“xyz:+tmp”);
    out.flush();
    }
    }捕获(IOException IOException){
    Log.d(“Robin”,“套接字侦听上的IOException:”+IOException);
    }
    捕获(例外e){
    Log.d(“Robin”,“外部异常:+e.toString());
    打破
    }
    最后{
    if(client==null | | client.isClosed()
    ||!client.isConnected()){
    Log.d(“Robin”,“客户端为空”);
    打破
    }
    }
    //中断;
    }
    Log.d(“罗宾”,“线程停止…”);
    }
    
    是的,可以将服务器或客户端上多个线程的数据写入现有套接字。但是,您必须确保请求不重叠,并且接收方实际上知道从谁那里写入的内容

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

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

    也许本教程有帮助?有很多:


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

    在上面的代码中,我只是又开始了一个线程来编写

    在上述代码的运行函数中插入代码

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