如何保持套接字连接直到服务器处理它?

How to keep Socket Connection until Server Process it?

我在写Socket程序,这里Client通过Stream发送一个String,Server处理后回写给Client。我的问题是,在服务器处理 String 之后,它写回 Stream 但在客户端它无法读取 Stream 其显示异常为 Exception in while: java.net.SocketException: socket closed 这是我的代码,

客户,

  public void run() {
    while (true) {
        try {
            // Open your connection to a server, at port 1231
            s1 = new Socket("localhost", 1231);

            OutputStream s1out = s1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(s1out);
            InputStream in=s1.getInputStream();
            DataInputStream dis=new DataInputStream(in);

            String s = br.readLine();
         dos.writeUTF(s);
         dos.flush();
         dos.close();

            System.out.println(dis.readUTF());//it is the String from Server after processing
            dis.close();

        } catch (IOException ex) {
            //  Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Exception in while: " + ex);
        }
    }

在服务器中

  public void run()
    {


        while(true){
            try {

                 System.out.println("Waiting for connect to client");
                 s1=serverSocket.accept();


                 s1In = s1.getInputStream();
                 dis = new DataInputStream(s1In);

                 out=s1.getOutputStream();
                 dos=new DataOutputStream(out);

                 String clientData=dis.readUTF();

                 //processing task String

              dos.writeUTF("Bus Registered Successfully");
              dos.flush();

            }
          }

这里我无法在客户端读取 Bus Registered Successfully。如何解决这个问题?

快速浏览显示套接字关闭的原因是因为您使用了 dos.close()

关闭 DataInputStream(或 PrintStream,或任何类似的流)将关闭底层套接字。

取出dos.close()即可。

您还可以将 dos.close() 移动到 try 块的最后。作为一般规则,在完成套接字之前不要关闭与套接字相关的任何内容。

嗯,你的程序有很多不对的地方。但首先让我回答你的问题......你在写入流后立即关闭套接字......所以服务器抛出异常,只需在 dos.flush(); 之后删除 dos.close();。它会 运行 没问题。

现在回到编程实践...

1) 服务器应在 while(true) 循环中接受连接,然后创建一个新线程。所以下面的语句应该 而不是 run 方法的一部分。

             System.out.println("Waiting for connect to client");
             s1=serverSocket.accept();


             s1In = s1.getInputStream();
             dis = new DataInputStream(s1In);

             out=s1.getOutputStream();
             dos=new DataOutputStream(out);

2)client不需要run方法。因为每个新客户都是一个新程序,有自己的 variablessocket.