创建客户端 - 服务器聊天程序

时间:2011-11-10 13:04:36

标签: java client chat objectinputstream

在使用对象流的服务器客户端聊天程序中,我如何能够向所有客户端发送消息以及向某些客户端发送私有消息?

在我的侦听连接方法中,我接受连接

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.

我如何以及在何处保留已连接客户的列表?

我想到了一个hastable,密钥是用户名和ObjectOutPutStream。然后读取连接被接受后发送的对象,但我遇到了问题。该消息是一个登录命令,提供用户名和命令LOGIN

我的代码变成了;

  

System.out.println(“等待连接”);                   Socket client = servSocket.accept();                   System.out.println(“Connection From:”+ 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;
    }
}

1 个答案:

答案 0 :(得分:0)

以下代码对我来说非常适合。请注意,Server类必须能够访问其类路径中的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());
    }
}