在使用对象流的服务器客户端聊天程序中,我如何能够向所有客户端发送消息并将私人消息发送给某些客户端?
在我的监听连接方法中,我接受连接
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();
}
}
然后我将此客户端传递给服务器中的一个线程来处理消息交换;
IE;
//pass message handling to thread and listen ClientHandler handler = new ClientHandler(client,this); handler.start();//As usual, this method calls run.
我如何以及在哪里保留已连接客户端的列表?
我想到了一个hastable,键是用户名和ObjectOutPutStream。然后在连接被接受后读取正在发送的对象,但我遇到了问题。该消息是一个登录命令,给出了用户名和一个命令 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; } }