2014-04-12 2 views
0

하나의 서버가 여러 클라이언트에서 수신 한 메시지를 모든 클라이언트에 브로드 캐스팅하는 다중 채팅 클라이언트 서버 응용 프로그램을 개발했습니다 : 문제는 코드가 다음 코드 줄에서 진행되지 않는다는 것입니다 , 개별 클라이언트는 서버로부터 메시지를 다시받지 못합니다. 이 코드는 언제 작동합니까? 이 코드는 단일 클라이언트 서버 응용 프로그램에서만 작동합니다.다중 스레드 Java 클라이언트 서버 문제

누군가이 응용 프로그램에 어떤 문제가 있는지 알려주세요. 코드의

LINE : 여러 클라이언트가 실행되는 MultiClient.java에서 이후

din = new DataInputStream(clientSocketRecv.getInputStream()); 

. 코드는 다음과 같다 :

Client.java

/** 
* 
*/ 
package Client_Package; 

import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 




/** 
* @author sanika 
* 
*/ 

//Client will communicate with the server 
public class Client implements Runnable{ 

private BufferedReader stdIn; 
private BufferedReader in; 
private DataInputStream din; 
private DataOutputStream dout; 
private static Socket clientSocket; 
Thread t; 
/** 
* @param args 
*/ 

@Override 
public void run() { 
    System.out.println("I am in the thread"); 
    readFromServer(); 

} 


private void readFromServer() { 
    try { 
     System.out.println("Reading frm server"); 
     din= new DataInputStream(clientSocket.getInputStream()); 
     System.out.println("Client Socket value is" + clientSocket); 
     System.out.println("Reading from the socket" + din.readUTF()); 
     while(din.readUTF() != null) { 
      System.out.println("Echo from server" + din.readUTF()); 
     } 
    } catch(IOException ioexp) { 

    } 

} 

private void startClient(BufferedReader stdIn, DataOutputStream dout) { 
    String textFromServer = new String(); 
    String userInput= new String(); 

    try { 
     if((userInput = stdIn.readLine()) != null) { 
      //Sent it to the Server 
      System.out.println("Sent to the server" + userInput); 
      if(userInput.equalsIgnoreCase("Bye")) { 
       System.out.println("Client exited"); 
       System.exit(1); 
      } 
      System.out.println("Gonna write to the server"); 
      dout.writeUTF(userInput); 
      dout.flush(); 
     } 


    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    String host = args[0]; 
    int port = Integer.parseInt(args[1]); 
    String textFromServer = new String(); 
    String userInput= new String(); 
    Client clientObj = new Client(); 
    if (args.length != 2) { 
      System.err.println("Usage: java EchoServer <port number>"); 
      System.exit(1); 
    } 


    try { 
     clientObj.clientSocket = new Socket(host,port); 
     clientObj.dout = new DataOutputStream(clientObj.clientSocket.getOutputStream()); 
     clientObj.in = new BufferedReader(new InputStreamReader(clientObj.clientSocket.getInputStream())); 
     clientObj.stdIn = new BufferedReader(new InputStreamReader(System.in)); 

     System.out.println("Thread created!!"); 
     (new Client()).startClient(clientObj.stdIn,clientObj.dout); 
     Thread t = new Thread(new Client()); 
     t.start(); 


    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

} 

에게 Server.java

/** 
* 
*/ 
package Server_Package; 

import java.io.BufferedReader; 
import java.io.Console; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.util.Vector; 

/** 
* @author sanika 
* 
*/ 
public class Server { 

/** 
* @param args 
*/ 
static Vector clientSockets; 
public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    //Accepting input from the console 
    int portNumber = Integer.parseInt(args[0]); 
    clientSockets = new Vector(); 
    if (args.length != 1) { 
      System.err.println("Usage: java EchoServer <port number>"); 
      System.exit(1); 
    } 

    clientSockets = new Vector(); 
    boolean listening = true; 
    try { 
     //while(listening) { 
      ServerSocket serverSocket = new ServerSocket(portNumber); 
      while(true) { 
       MultiClient multiC = new MultiClient(serverSocket.accept(), clientSockets); 
      } 

    } catch(IOException e) { 
     System.out.println("Exception caught when trying to listen to the client port" + portNumber + "or listening for a connection"); 
     System.out.println(e.getMessage()); 
    } 


} 

} 

MultiClient.java

/** 
* 
*/ 
package Server_Package; 

import java.io.BufferedReader; 
import java.io.Console; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.Socket; 
import java.nio.channels.SocketChannel; 
import java.util.Vector; 

/** 
* @author sanika 
* 
*/ 
public class MultiClient implements Runnable { 

private Socket clientSocket; 
private static int count = 0; 
private DataOutputStream dout; 
private DataInputStream din; 
static Vector clientSockets; 
private Thread t; 
public MultiClient() { 

} 

public MultiClient(Socket clientSocket, Vector clientSockets) { 
    System.out.println("Came into the MultiClient constructor"); 
    this.clientSocket = clientSocket; 
    this.clientSockets = clientSockets; 
    try { 
     t = new Thread(new MultiClient()); 

     System.out.println("Added this socket to the list in MultiChatClient" + this.clientSocket); 

     clientSockets.add(this.clientSocket); 
     t.start(); 

    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

@Override 
public void run() { 

    try { 
     //dout = new DataOutputStream(this.clientSocket.getOutputStream()); 
     //din = new DataInputStream(this.clientSocket.getInputStream()); 
     DataOutputStream tdout= null; 
     String inputLine=""; 
     System.out.println("Came into the run method in the MultiCHatClient class"); 
     count++; 
     System.out.println("The clientSockets size" + clientSockets.size()); 

     for(int i=0; i < clientSockets.size() ; i++) { 
        //Assigned a new Socket to each client to initiate data transfer 

        Socket clientSocketRecv = (Socket)(clientSockets.get(i)); 
        System.out.println("Client Socket" + clientSocketRecv); 

        din = new DataInputStream(clientSocketRecv.getInputStream()); 
        String message= null; 
        System.out.println("Reading from the client" + din.readUTF()); 
        while((message = din.readUTF()) != null) { 
         this.dout = new DataOutputStream(clientSocketRecv.getOutputStream()); 
         System.out.println("From Server" + "For Client" + count + message); 
         this.dout.writeUTF("From Server" + "For Client" + count + message); 
         this.dout.flush(); 
         } 

       } 



    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

} 
+0

방법이 실행합니까? > 실행 중 : java -client -cp.Client_Server 는 MultiChatClientSocket의 목록에이 소켓을 추가되었습니다 멀티 클라이언트 생성자 에 온 [요지 =/127.0.0.1, 포트 = 56266, localport = 8080] 는 MultiCHatClient 클래스 clientSockets 크기 1 클라이언트 SocketSocket의 실행 방법에 온 [addr =/127.0.0.1, port = 56266, localport = 8080] 작성된 스레드! 메인 종료 0 오류 – NormR

+0

맞습니다. 각 클라이언트에 대해 127.0.0.1을 입력하고 서버의 포트는 6000이 될 수 있습니다. 따라서 클라이언트 1의 경우 입력은 127.0.0.1 6000입니다. 클라이언트 2의 경우 입력은 127.0.0.1 6000이됩니다. – MindBrain

답변

0

왜 새 개체를 만드는을 MultiClient ~ s 새 스레드를 씹으시겠습니까?

사용

t = new Thread(this); 

대신 MultiClient 파일

t = new Thread(new MultiClient()); 

의.


나는 문제가 MultiClient 파일의 아래 줄에 있다고 생각합니다.

System.out.println("Reading from the client" + din.readUTF()); 
while((message = din.readUTF()) != null) { 
  • 먼저 SOP의 라인 형태의 클라이언트를 읽었습니다. 이제 클라이언트에게이 줄을 전달할 것을 기대하지만, din.readUTF()의 다음 호출은 while SOP에서 이미 첫 줄을 사용했기 때문에 클라이언트가 한 줄 더 입력 할 때까지 기다립니다. 다시 확인하십시오.
  • 대기 상태의 스레드가 어디에 있는지 찾아보십시오.

나는 Client Server communcation에 대한 몇 가지 샘플을 게시했다. 좀 더 살펴보고 더 많은 샘플을 찾으려면 게시물을 따르십시오. 그것은 클라이언트 & 서버간에 통신하는 방법을 안내합니다.

1

는 여기에 테스트 클라이언트에 사용하는 운전자의 - 서버 프로그램 :

public static void main(final String[] args) { 
    Thread t1 = new Thread(new Runnable() { 
    public void run() { 
     try{Server.main(new String[]{"8080"});}catch(Exception x){x.printStackTrace();} 
    } 
    }); 
    t1.start(); 

    try{Thread.sleep(100);}catch(Exception x){} 

    Thread t2 = new Thread(new Runnable() { 
    public void run() { 
     try{Client.main(new String[]{"127.0.0.1", "8080"});}catch(Exception x){x.printStackTrace();} 
    } 
    }); 
    t2.start(); 

    Thread t3 = new Thread(new Runnable() { 
    public void run() { 
     try{Client.main(new String[]{"127.0.0.1", "8080"});}catch(Exception x){x.printStackTrace();} 
    } 
    }); 
    t3.start(); 

    // wait and exit Change time to suit -To catch runaway code 
    try{Thread.sleep(5000);}catch(Exception x){} 
    System.out.println("Exiting main"); 
    System.exit(0); 

} // end main()>>>>>>>>>>>>>>>>>>>>>>>>>>