java聊天室(单人)2.0

客户端:

package talktest;
import java.io.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;

import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class SingleTalkClient implements ActionListener
{
    JFrame f=new JFrame("QQ Client");
    JButton b=new JButton("sending");
    JTextArea show=new JTextArea(10,50);
    JTextField send=new JTextField(50);
    JScrollPane jsp1=new JScrollPane(show);
    //JScrollPane jsp2=new JScrollPane(send);
    JPanel southPanel=new JPanel(new BorderLayout());
    JPanel northPanel=new JPanel(new BorderLayout()); 
    //JPanel p1=new JPanel() ;
    //JPanel p2=new JPanel() ;
    String fromServer, fromUser;
    boolean sbye = false;
    boolean ubye = false;
    Socket client = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String record;
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==b){
            if(send.getText().equals(""))  
            {  
                JOptionPane.showMessageDialog(null, "消息不能为空");  
            }
            else if(ubye==false){
                fromUser=send.getText();
                fromUser=fromUser.replace("Client input:","");
                record=record+"from Client:"+fromUser+"\n";//将发送语句中的Client input:去掉
                show.setText(record);
                out.println(fromUser);
                //out.flush();
                if(fromUser.equals("Bye.")){
                    ubye=true;
                }
            }
            send.setText("");
        }
    }
    public void fun()throws IOException{
        northPanel.setBorder(new TitledBorder("消息显示")); 
        northPanel.add(jsp1, "Center");
        southPanel.setBorder(new TitledBorder("写消息"));  
        southPanel.add(send, "Center");  
        southPanel.add(b,"East");
        show.setEditable(false);
        //f.setContentPane(p1);
        f.setSize(600,550);
        //f.add(show);
          //f.add(send);
        f.setLayout(new BorderLayout());  
        f.add(northPanel, "North");  
        f.add(southPanel, "South"); 
        //f.add(jsp1, BorderLayout.CENTER);
        //f.add(jsp2, BorderLayout.CENTER);
        //f.add(b);
          f.setBackground(Color.GRAY);
          //f.setLayout(new FlowLayout(FlowLayout.CENTER));
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;  
        int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height; 
        f.setLocation((screen_width - f.getWidth()) / 2,(screen_height - f.getHeight()) / 2);  
        f.setResizable(false);//无法调整大小
        f.setVisible(true);
        b.addActionListener(this);
        send.addKeyListener(new KeyAdapter() {//回车发送
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode()==KeyEvent.VK_ENTER)
                {
                    if(send.getText().equals(""))  
                    {  
                        JOptionPane.showMessageDialog(null, "消息不能为空");  
                    }
                    else if(ubye==false){
                        fromUser=send.getText();
                        fromUser=fromUser.replace("Client input:","");
                        record=record+"from Client:"+fromUser+"\n";//将发送语句中的Client input:去掉
                        show.setText(record);
                        out.println(fromUser);
                        //out.flush();
                        if(fromUser.equals("Bye.")){
                            ubye=true;
                        }
                    }
                    send.setText("");
                }
            }
        });
        try {
            client = new Socket("127.0.0.1",4444);
            out = new PrintWriter(client.getOutputStream(), true); //auto flush
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: 127.0.0.1.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: 127.0.0.1.");
            System.exit(1);
        }
            
        //从标准输入流(键盘)中获取信息
    //BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
      
    record="";
    send.setText("");
    /*
    if(fromServer.equals("Bye.")){
        sbye=true;
    }
    record=record+"from Server:"+fromServer+"\n";
    show.setText(record);
    if(sbye){
        ubye=true;
        out.println("Bye.");
        out.flush();
    }
    else{
        send.setText("Client input:");
        */
    //System.out.print("Client input:");
    //fromUser = stdIn.readLine();
        while( true )  
    {
            //send.setText("Client input:");
            if( sbye == false )
            {
                fromServer=in.readLine();
                record=record+"from Server:"+fromServer+"\n";
                show.setText(record);
                //fromServer = in.readLine();
                //System.out.println("from Server: " + fromServer);
                if (fromServer.equals("Bye."))
                    sbye = true;
            }
        if( ubye == false )
        {
            //out.println(fromUser);
            //out.flush();
            //System.out.println("Client: " + fromUser);
            //if (fromUser.equals("Bye."))
            //ubye = true;
            if(sbye==true){
                out.println("Bye.");
                out.flush();
                ubye=true;
            }
            else
                send.setText("");
        }

        
        //if( ubye == false )
        //{
        //    System.out.print("Client input:");
        //    fromUser = stdIn.readLine();
        //}

        if( ubye == true && sbye == true )
            break;
        }

        out.close();
        in.close();
        //stdIn.close();
        client.close();
    }
    private void add(JScrollPane jsp12, String center) {
        // TODO Auto-generated method stub
        
    }
    public static void main(String[] args) throws IOException
    {
        new SingleTalkClient().fun();
        
    }
}

服务器端:

package talktest;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class SingleTalkServer implements ActionListener
{

    JFrame f=new JFrame("QQ Server");
    JButton b=new JButton("sending");
    JTextArea show=new JTextArea(10,50);
    JTextField send=new JTextField(50);
    JScrollPane jsp1=new JScrollPane(show);
    //JScrollPane jsp2=new JScrollPane(send);
    JPanel southPanel=new JPanel(new BorderLayout());
    JPanel northPanel=new JPanel(new BorderLayout()); 
    boolean  sinbye = false;
    boolean  inbye = false;
    String sinputLine, inputLine;
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    String record;
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==b){
            if(send.getText().equals(""))  
            {  
                JOptionPane.showMessageDialog(null, "消息不能为空");  
            }
            else if(sinbye==false){
                sinputLine=send.getText();            
                sinputLine=sinputLine.replace("Server input:","");
                record=record+"from Server:"+sinputLine+"\n";//将发送语句中的Client input:去掉
                show.setText(record);
                out.println(sinputLine);
                //out.flush();
                if(sinputLine.equals("Bye.")){
                    sinbye=true;
                }
            }
            send.setText("");
        }
    }
    public void fun()throws IOException{
        northPanel.setBorder(new TitledBorder("消息显示")); 
        northPanel.add(jsp1, "Center");
        southPanel.setBorder(new TitledBorder("写消息"));  
        southPanel.add(send, "Center");  
        southPanel.add(b,"East");
        show.setEditable(false);
        f.setSize(600,550);
        f.setLocation(500, 100);
        //f.add(show);
          //f.add(send);
          //f.add(jsp1, BorderLayout.CENTER);
          //f.add(send, BorderLayout.CENTER);
          //f.add(b);
        f.setLayout(new BorderLayout());  
        f.add(northPanel, "North");  
        f.add(southPanel, "South"); 
          f.setBackground(Color.GRAY);
        //f.setLayout(new FlowLayout(FlowLayout.CENTER));
        f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
            }
        });
        int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;  
        int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height; 
        f.setLocation((screen_width - f.getWidth()) / 2,(screen_height - f.getHeight()) / 2);  
        f.setVisible(true);
        b.addActionListener(this);
        send.addKeyListener(new KeyAdapter() {//回车发送
            public void keyPressed(KeyEvent e) {
                if(e.getKeyCode()==KeyEvent.VK_ENTER)
                {
                    if(send.getText().equals(""))  
                    {  
                        JOptionPane.showMessageDialog(null, "消息不能为空");  
                    }
                    else if(sinbye==false){
                        sinputLine=send.getText();            
                        sinputLine=sinputLine.replace("Server input:","");
                        record=record+"from Server:"+sinputLine+"\n";//将发送语句中的Client input:去掉
                        show.setText(record);
                        out.println(sinputLine);
                        //out.flush();
                        if(sinputLine.equals("Bye.")){
                            sinbye=true;
                        }
                    }
                    send.setText("");
                }
            }
        });
        
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }

        
        try {
            clientSocket = serverSocket.accept();  //程序将在此等候客户端的连接
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }
        show.setText("Accept OK!"+"\n");
                

    //从标准输入流(键盘)中获取信息
        //BufferedReader sin = new BufferedReader( new InputStreamReader( System.in ) );

        //打开输入/输出流
        out = new PrintWriter(clientSocket.getOutputStream(), true);  //auto flush
        in = new BufferedReader(
                new InputStreamReader(
                clientSocket.getInputStream()));
    
        record="";
        //send.setText("Server input:");
        inputLine = in.readLine();
        //System.out.println( "from Client: " + inputLine );
        if(inputLine.equals("Bye.")){
            inbye=true;
        }
        record=record+"from Client:"+inputLine+"\n";
        show.setText(record);
        if(inbye){
            sinbye=true;
            out.println("Bye.");
            out.flush();
        }
        else{
            send.setText("");
        }
        //System.out.print("Server input:");
        //sinputLine = sin.readLine();

        while( true )
        {
            //send.setText("Server input:");
            if( inbye == false )
            {
                inputLine = in.readLine();
                //System.out.println( "from Client: " + inputLine );
                record=record+"from Client:"+inputLine+"\n";
                show.setText(record);
                if (inputLine.equals("Bye."))
                    inbye = true;
            }
            if( sinbye == false )
            {
            //out.println(sinputLine);
            //out.flush();
            //System.out.println("Server: " + sinputLine);

            //if (sinputLine.equals("Bye."))
                //sinbye = true;
                if(inbye==true){
                    out.println("Bye.");
                    out.flush();
                    sinbye=true;
                }
                else
                    send.setText("");
            }
        //if( sinbye == false )
        //{
            //System.out.print("Server input:");
            //sinputLine = sin.readLine();
        //}

            if( sinbye == true && inbye == true )
                break;
        }

        out.close();
        in.close();
        //sin.close();
        clientSocket.close();
        serverSocket.close();
    }
    public static void main(String[] args) throws IOException
    {
        new SingleTalkServer().fun();
    }
}

 

posted @ 2017-04-03 21:14  奇热行  阅读(423)  评论(0)    收藏  举报