-2

我是 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();

    }        
}
}
4

2 回答 2

0

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

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

相反,其中的逻辑可能有问题

if(!"".equals(msg)) {
     PrintStrims.println(dateFormat.format(date)+": "+msg);
}

您可能想确保您实际上可以进入该声明

于 2012-11-23T04:46:37.147 回答
0

对于聊天服务器和客户端,我建议使用OpenFire服务器和SmackAPI。例如,这是一个很好的参考Smack下载 OpenFire服务器。

于 2012-11-23T04:21:05.530 回答