如何在服务器处理之前保持套接字连接?

时间:2015-01-13 08:58:11

标签: java sockets serversocket

我正在编写Socket程序,Here客户端通过Stream发送字符串,Server处理它并写回客户端。我的问题是,在服务器处理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。如何解决这个问题。?

2 个答案:

答案 0 :(得分:1)

你的程序中有很多不对的东西。但首先让我回答你的问题......你在写完流之后就关闭了套接字......所以服务器抛出异常,只需在dos.close();之后删除dos.flush();。它会运行良好。

现在回到编程实践......

1)服务器应该在while(true)循环中接受连接,然后创建一个新线程。因此,以下语句 not 应该是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) run中{em>不需要 client方法。因为每个新客户都是一个拥有自己的variablessocket的新程序。

答案 1 :(得分:0)

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

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

只需取出dos.close()

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

相关问题