2012-02-22 104 views
1

我有一個相對簡單的程序,我嘗試建立客戶端服務器連接,同時我使用客戶端的線程來允許多個連接。從服務器到客戶端的套接字通信困難

我運行服務器,然後服務器調用客戶端構造函數,並將端口連接傳遞給客戶端,並在客戶端啓動該線程。

我遇到的問題是,當我運行服務器端時,它不想超越構造函數調用。它似乎卡住了構造函數。

對不起這一切聽起來有點混亂

任何想法也許

這是服務器端

ServerMultipleThreads() 
{ 


    System.out.println("Starting the server first..."); 
    try 
    { 
     ServerSoc = new ServerSocket(7777); 
     listening = true; 

    } 
    catch(Exception e) 
    { 
     System.out.println(e.toString()); 
     System.exit(1); 

    } 

    System.out.println("The server has started running"); 

    while(listening) 
    { 
     try 
     { 
      //creating the client socket and starting the new client session 
      new ClientSession(ServerSoc.accept()); 
      System.out.println("The clientSession was called"); 
      in = new DataInputStream(clientSocket.getInputStream()); 
      BufferedReader is = new BufferedReader(new InputStreamReader(in)); 
      os = new PrintStream(clientSocket.getOutputStream()); 

      while(true) 
      { 
       line = is.readLine(); 
       PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myFile,txt")), true); 
       out.println(line); 
      } 


     } 
     catch(IOException ioe) 
     { 
       System.out.println(ioe.toString()); 
     } 
    } 

} 

,這是在客戶端

ClientSession(Socket s) 
{ 
    clientSocket = s; 

    try 
    { 


     out = new PrintWriter(clientSocket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     out.println("Welcome"); 

    } 
    catch(IOException exe) 
    { 
     System.out.println(exe.toString()); 

    } 
    //starting the thread 
    while(runner == null) 
    { 
     runner = new Thread(this); 
     runner.start(); 
    } 
} 

public void run() 
{ 
    while(runner == Thread.currentThread()) 
    { 
     BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); 
     String stdIn; 

     try 
     { 
      while((stdIn = buf.readLine()) != null) 
      { 
       out.println(stdIn); 
      } 
     } 
     catch(IOException exe) 
     { 
      exe.toString(); 

     } 
     try 
     { 
      Thread.sleep(10); 
     } 
     catch(InterruptedException e){} 

    } 

親切的問候 Arian

回答

1

這是因爲ServerSocket.accept()阻塞,直到它收到客戶端請求。 您需要有一個客戶端調用服務器,如下所示:

Socket socket = new Socket(host, port); 
InputStream in = socket.getInputStream(); 
// write some data...