Java聊天服务器 - 客户端

时间:2012-11-23 03:26:36

标签: java chat java-server

我是Java新手。我正在尝试用一个客户端制作一个简单的聊天应用程序,但有些东西是不对的......无法弄明白。在尝试收听时,它会在连接(紧接着它)之后卡在服务器上。想法很简单:客户端发送消息,服务器接收消息并将其发回。请帮忙......!

主要

public class main {
 public static void main(String[] args) {
    Server Server = new Server();
    Server.runServer();        

    Client client = new Client();
    client.runForm();
}  
}

服务器

public class Server {

public static int SERVERA_PORTS = 5432;
private static JTextArea txtMessages;
public static void main(String[] args) {

}

 public void runServer() {   
    //Form
    JFrame frame = new JFrame();
    txtMessages = new JTextArea();
    JPanel pnlContent = (JPanel) frame.getContentPane();
    pnlContent.setLayout(new BorderLayout());
    pnlContent.add(txtMessages, BorderLayout.CENTER);
    txtMessages.setEditable(false);
    frame.setSize(500, 400);
    frame.setLocation(100, 100);
    frame.setTitle("Console");
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setVisible(true);        
    txtMessages.append("Listening!\n*************************\n");

    ServerSocket serverSocket = null;
    try{
            serverSocket = new ServerSocket(SERVERA_PORTS);
    } catch (IOException ex){

            return;
    }

    while(true){
        Socket socket = null;
        try{
            socket = serverSocket.accept();
            System.out.println("Client: "+socket.getRemoteSocketAddress()+" connected");                        
            InputStreamReader IntputaReaders = new InputStreamReader(socket.getInputStream());
            BufferedReader BuferaReaders = new BufferedReader(IntputaReaders);

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();                             
            String msg = BuferaReaders.readLine();
            System.out.println(dateFormat.format(date)+": "+msg);   

            //Sends back to clint
            PrintStream PrintStrims = new PrintStream(socket.getOutputStream());
            if(!"".equals(msg)) {
                PrintStrims.println(dateFormat.format(date)+": "+msg);
            }   

            //Puts in GUI
            txtMessages.append(socket.getRemoteSocketAddress()+": "+msg+"\n");



        } catch (IOException ex){
        } finally {
                try{
                        socket.close();
                } catch (Exception ex){}
        }
    }
}

}

客户端

public class Client extends JFrame implements ActionListener {

private static JButton btnSend;
private static JButton btnConnect;
private static JTextArea txtMessages;
private static JTextField txtCurrentMessage;
private static JTextField txtServerPort;
private static JTextField txtServerName;

String hosts = "";
int ports;
Socket clientSocket = null;
BufferedReader in = null;

public static void main(String[] args) throws Exception {

}    

private void listen() {
    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String msgIn;
        while ((msgIn = in.readLine()) != null) {
            System.out.println(msgIn);
            txtMessages.append(msgIn+"\n");
        }        
    }catch (IOException ez) {

    }
}


public void connect(){        
      hosts = txtServerName.getText();        
      String strPort = txtServerPort.getText();
      ports = Integer.valueOf(strPort);                

    try{   
      //Ja pieslēdzas
      clientSocket = new Socket(hosts, ports);
      btnSend.setEnabled(true);
      txtMessages.append("U R connected!\n**************\n");
      btnConnect.setEnabled(false); 
      txtCurrentMessage.setEnabled(true);  

    } catch (IOException ex){
        txtMessages.append("Cannot connect.. \n");
    }    
}

public void send(){
    try{
        PrintStream PrintStrims = new PrintStream(clientSocket.getOutputStream());      
        String message = txtCurrentMessage.getText();
        PrintStrims.println(message);
        System.out.println(message); 

    } catch (IOException ex){
    }       
}

public void runForm() {
    JFrame frame = new JFrame();
    txtServerName = new JTextField();
    txtServerName.setPreferredSize(new Dimension(150, 21));
    txtServerPort = new JTextField();
    txtServerPort.setPreferredSize(new Dimension(50, 21));
    txtMessages = new JTextArea();
    txtCurrentMessage = new JTextField();
    txtCurrentMessage.setPreferredSize(new Dimension(350,21));
    btnConnect = new JButton("Connect");
    btnConnect.addActionListener(this);
    btnSend = new JButton("Send");
    btnSend.addActionListener(this);
    JPanel pnlTop = new JPanel(new FlowLayout());
    JPanel pnlBottom = new JPanel(new FlowLayout());
    pnlTop.add(txtServerName);
    pnlTop.add(txtServerPort);
    pnlTop.add(btnConnect);
    pnlBottom.add(txtCurrentMessage);
    pnlBottom.add(btnSend);
    JPanel pnlContent = (JPanel) frame.getContentPane();
    pnlContent.setLayout(new BorderLayout());
    pnlContent.add(pnlTop, BorderLayout.NORTH);
    pnlContent.add(txtMessages, BorderLayout.CENTER);
    pnlContent.add(pnlBottom, BorderLayout.SOUTH);
    frame.setLayout(new BorderLayout());
    frame.add(pnlTop, BorderLayout.NORTH);
    frame.add(txtMessages, BorderLayout.CENTER);
    frame.add(pnlBottom, BorderLayout.SOUTH);
    frame.setSize(500, 400);
    frame.setLocation(100, 100);
    frame.setTitle("Ne pārāk labs čats");
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    txtServerName.setText("127.0.0.1");
    txtServerPort.setText("5432");      
    btnSend.setEnabled(false);
    txtCurrentMessage.setEnabled(false);
    txtMessages.setEditable(false);
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btnSend) {  
        if(!"".equals(txtCurrentMessage.getText()))
        {
            send();          
            txtCurrentMessage.setText("");
        }
    }

    if (e.getSource() == btnConnect) {               
            connect();
            listen();

    }        
}
}

2 个答案:

答案 0 :(得分:0)

对于聊天服务器和客户端,我建议使用OpenFire服务器和Smack API。 HereSmack示例的一个很好的参考。 Download OpenFire服务器。

答案 1 :(得分:0)

了解您的服务器在连接后是否从客户端获取任何内容会很有帮助。这样我们就可以确定服务器是否没有收到要发回的消息,或者客户端是否没有收到返回消息。

这个oracle教程可能对你有所帮助,因为它看起来像是使用gui并且非常好地解释了客户端和服务器如何使用代码。 http://www.oracle.com/technetwork/java/socket-140484.html

相反,

中的逻辑可能有问题
if(!"".equals(msg)) {
     PrintStrims.println(dateFormat.format(date)+": "+msg);
}

您可能希望确保您可以实际进入该声明