java socket编程阻塞对服务器和客户端的读写操作

时间:2014-11-09 10:05:03

标签: java sockets iostream blocking serversocket

我在java中有客户端服务器套接字编程。

服务器:多线程服务器,为客户端提供数学计算服务,例如:客户端等提供的所有数字的总和....

客户端:是连接到服务器并选择指定的数学运算加法,减法... 等,并提供服务器返回结果的数字,也许结果是单个值,或者服务器的结果可能是数字数组,取决于操作的类型......

我的问题是:从服务器到客户端读取和写入阻塞,反之亦然 例如:

**server->client :*** Welcome to the Calculation Server
server->client: "*** Please type in the num of rows: \n"
client->server: the user insert num of rows and send it to server
server->client: "*** Please type in the num of cols: \n"
client->server: the user insert num of columns and send it to server
server->client:writer.write("Enter the elements of first matrix");
client->server: at the client side it blocks or hang i dont know y???**

服务器发送

服务器代码的一部分

import java.net.*; 
import java.io.*; 

class server_thread extends Thread
{ 
 protected Socket clientSocket;

 public static void main(String[] args) throws IOException 
   { 
    ServerSocket serverSocket = null; 
    int port=10008;
    try { 
         serverSocket = new ServerSocket(port); 
         System.out.println ("Connection Socket Created on port : "+port);
         try { 
              while (true)
                 {
                  System.out.println ("Waiting for Connection");
                  new server_thread (serverSocket.accept()); 
                 }
             } 
         catch (IOException e) 
             { 
              System.err.println("Accept failed."); 
              System.exit(1); 
             } 
        } 
    catch (IOException e) 
        { 
         System.err.println("Could not listen on port: 10008."); 
         System.exit(1); 
        } 
    finally
        {
         try {
              serverSocket.close(); 
             }
         catch (IOException e)
             { 
              System.err.println("Could not close port: 10008."); 
              System.exit(1); 
             } 
        }
   }

 private server_thread (Socket clientSoc)
   {
    clientSocket = clientSoc;
    start();
   }

 public void run()
   {
    System.out.println ("New Communication Thread Started");

    try { 
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter writer= 
                    new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

    String sinput_row, sinput_col,srow_count, scol_count;
    int row_count, col_count;

            writer.write("*** Welcome to the Calculation Server ( ***\r\n");            




 ////////////////////////////////////////////////////////////////////////////////////////////////
              writer.write("*** Please type in the num of rows: \n");
              writer.flush();
              sinput_row = reader.readLine().trim();
              int input_row=Integer.parseInt(sinput_row);
              System.out.println("num of rows got:"+input_row); 

 //////////////////////////////////////////////////////////////////////////////////////////////////////



 ////////////////////////////////////////////////////////////////////////////////////////////////
              writer.write("*** Please type in the num of cols: \n");
              writer.flush();
              sinput_col = reader.readLine().trim();
              int input_col=Integer.parseInt(sinput_col);
              System.out.println("num of Cols got:"+input_col); 

 //////////////////////////////////////////////////////////////////////////////////////////////////////


  ////////////////////////////////////////////////////////////////////////////////////////////////

  writer.write("Enter the elements of first matrix");
  writer.flush();

   int first[][] = new int[input_row][input_col];
      int second[][] = new int[input_row][input_col];
      int sum[][] = new int[input_row][input_col];

      for (  row_count = 0 ; row_count < input_row ; row_count++ )
         for ( col_count = 0 ; col_count < input_col ; col_count++ )
         {
             String s_matrix1_element=reader.readLine().trim();
             int matrix1_element=Integer.parseInt(s_matrix1_element);
            first[row_count][col_count] = matrix1_element; 

         }


  // the rest of code is ommited for simplicty of analysis

   ////////////////////////////////////////////////////////////////////////////////////////////////


            //int result=num1+num2;            
            System.out.println("Addition operation done " );

             writer.flush();
             writer.write("");

            //writer.write("\r\n=== Result is  : "+result);
            writer.flush();
            clientSocket.close();
        } 
    catch (IOException e) 
        { 
         System.err.println("Problem with Communication Server");
         System.exit(1); 
        } 
    }
} 

这是客户端代码:

import java.io.*;
import java.net.*;
import java.util.*;

public class client_thread {

   public static void main(String argv[])
      {
       try{
            Socket socketClient= new Socket("localhost",10008);
            System.out.println("Client: "+"Connection Established");

            BufferedReader reader = 
                    new BufferedReader(new InputStreamReader(socketClient.getInputStream()));

            BufferedWriter writer= 
                    new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));

            BufferedReader stdIn = new BufferedReader(
                                   new InputStreamReader(System.in));
            String serverMsg;
            String userInput;

            writer.flush();
            serverMsg = reader.readLine();
            System.out.println("from server: " + serverMsg);
            while((serverMsg = reader.readLine()) != null   )
            {


                System.out.println("from server inside loop: " + serverMsg);

                userInput = stdIn.readLine();
                 writer.write(userInput+"\r\n");
                  writer.flush();


            }

       }catch(Exception e){e.printStackTrace();}
      }
}

所以问题

2 个答案:

答案 0 :(得分:0)

您的服务器写道:

writer.write("Enter the elements of first matrix");

客户端使用

读取此内容
while((serverMsg = reader.readLine()) != null)

因此,由于服务器不发送任何行尾,客户端会等待它。

答案 1 :(得分:0)

方法1: 使用1个线程来处理输入流,使用另一个线程来处理输出流。然后你可以同时读写。

方法2: 使用NIO(非阻塞I / O)。