2011-11-10 3 views
1

개체 스트림을 사용하는 서버 클라이언트 채팅 프로그램에서 모든 클라이언트에게 메시지를 보내고 특정 클라이언트에게 개인 메시지를 보낼 수있는 방법은 무엇입니까? 연결 방법에 대한 내 듣기클라이언트 - 서버 채팅 프로그램 만들기

는 내가 메시지 exhanges을 처리 할 수있는 서버의 스레드에이 클라이언트를 통과 그런 다음 연결

public void listenForConnections() 
{ 
    String sUserName=""; 

    try{ 
     do { 
      System.out.println("Waiting on connections"); 
      Socket client = servSocket.accept(); 
      System.out.println("Connection From: " + client.getInetAddress());   


      //pass message handling to thread and listen 
      ClientHandler handler = new ClientHandler(client,this); 
      handler.start();//As usual, this method calls run.     

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

을 받아;

i, e;

  //pass message handling to thread and listen 
      ClientHandler handler = new ClientHandler(client,this); 
      handler.start();//As usual, this method calls run. 

어떻게 그리고 난 연결된 클라이언트의 목록을 유지합니까?

나는 사용자 이름과 ObjectOutPutStream 인 키를 가진 hastable을 생각했다. 그리고 연결이 허용 된 후에 전송되는 객체를 읽지 만 문제가 발생했습니다. 이 메시지는 사용자 이름과 명령을 제공하는 로그인 명령이었습니다. LOGIN

내 코드가되었습니다.

System.out.println ("연결 대기 중"); 소켓 클라이언트 = servSocket.accept(); System.out.println ("연결 원본 :"+ client.getInetAddress()); 이 손상 스트림에 대한 오류, 어떤 아이디어를 내 주면서

  ObjectOutputStream clientOOS = new ObjectOutputStream(client.getOutputStream()); 

      outputStreams.put(sUserName, oos); 


      //big problem here 
      //serializeation 
      /*ois = new ObjectInputStream(client.getInputStream()); 
      oos = new ObjectOutputStream(client.getOutputStream()); 

      //ask for the username /authenticate 
      System.out.println("SERVER: getting username"); 
      myMessage inMessageLogin = (myMessage) ois.readObject(); 

      if(inMessageLogin.getCOMMAND()==ServerCommands.CMD_LOGIN) 
      { 
       sUserName=inMessageLogin.getsUserName(); 
       System.out.println("SERVED User " + sUserName + " connected."); 
       //save stream 
       outputStreams.put(sUserName, oos); 
       //oos.close(); 
       //oos.flush(); 
       //ois.close(); 
       ois=null; 
       //oos=null; 
      } 
  //end of problem!!!!!*/ 

은 내가 주석 무엇입니까?

감사합니다.

클라이언트에서 서버로 메시지를 보내려면 다음을 입력하십시오.

//default cmd is to send to all 
public void sendMessage(String sText,int iCommand) 
{ 
    System.out.println("sendMessage"); 

    outMessage=new myMessage(); 

    outMessage.setsUserName(sCurrentUser); 
    //set command 
    outMessage.setCOMMAND(iCommand); 

    outMessage.setsMessage(sText); 

    System.out.println("send msg" + outMessage.displayMessage()); 

    try { 
     oos.writeObject(outMessage); 
     oos.flush(); 
     oos.reset(); 
     //clear up send message from txbox 
     txtMessage.setText(""); 
    } catch (IOException ex) { 
     Logger.getLogger(myClientGUI.class.getName()).log(Level.SEVERE, null, 

예); } } 서버에 연결

클라이언트 코드;

public void connectToServer() 
{ 
    String sServer=txtServer.getText(); 
    PORT=Integer.parseInt(txtPort.getText()); 
    try { 
     //host = InetAddress.getByName("localhost");//InetAddress.getLocalHost(); 
     host = InetAddress.getByName(sServer); 
     clientSocket = new Socket(host, PORT); 
    } 
    catch (Exception e){ 
     e.printStackTrace(); 
    } 
} 

public boolean createStreams() 
{ 
    try{ 
     //serial 
     //******************************************************************************* 
     // open I/O streams for objects - serialization streams 
     oos = new ObjectOutputStream(clientSocket.getOutputStream()); 
     ois = new ObjectInputStream(clientSocket.getInputStream()); 



     return true; 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
     return false; 
    } 
} 
+0

, 당신은 네트워크에 명령을 기록 클라이언트 코드를 제공해야합니다. –

+0

클라이언트에서 내 send 메소드를 게시했습니다. –

+0

클라이언트 코드에서 클라이언트 연결 및 ObjectOutputStream을 어떻게 작성합니까?이 클라이언트 코드도 게시 할 수 있습니까? –

답변

0

다음 코드는 완벽하게 나를 위해 잘 작동합니다. Server 클래스는 classpath에있는 Message 클래스에 액세스 할 수 있어야하며 Message 클래스는 Serializable을 구현해야합니다.

클라이언트 :

class Client { 
    private Socket clientSocket; 

    public void connectToServer() 
    { 
     String sServer="localhost"; 
     int PORT = 8181; 
     try { 
      InetAddress host = InetAddress.getByName(sServer); 
      clientSocket = new Socket(host, PORT); 
     } 
     catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 

    public void sendMessage(String sText,int iCommand) throws IOException { 
     Message outMessage = new Message(); 

     outMessage.setCOMMAND(iCommand); 
     outMessage.setsMessage(sText); 

     ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream()); 
     try { 
      oos.writeObject(outMessage); 
      oos.flush(); 
      oos.reset(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) { 
     Client c = new Client(); 
     c.connectToServer(); 
     try { 
      c.sendMessage("test message", 42); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

class Message implements Serializable { 
    private int iCommand; 
    private String sText; 

    public void setCOMMAND(int iCommand) { 
     this.iCommand = iCommand; 
    } 

    public void setsMessage(String sText) { 
     this.sText = sText; 
    } 

    @Override 
    public String toString() { 
     return "Message{" + 
       "iCommand=" + iCommand + 
       ", sText='" + sText + '\'' + 
       '}'; 
    } 
} 

서버 :

것 같아요
class Server { 
    public static void main(String[] args) throws IOException { 
     ServerSocket serverSocket = new ServerSocket(8181); 

     do { 
      Socket s = serverSocket.accept(); 
      try { 
       processClient(s); 
      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } while (true); 
    } 

    private static void processClient(Socket s) throws IOException, ClassNotFoundException { 
     ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); 
     Message message = (Message) ois.readObject(); 
     System.out.println(message.toString()); 
    } 
} 
관련 문제