java聊天室(多人)2.1

服务器端:

package talktest;
import java.net.*;
import java.text.SimpleDateFormat;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.util.*;
public class MultiTalkServer  
{
    public ArrayList<MultiTalkServerThread> clients = new ArrayList<MultiTalkServerThread>();
    public SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public Date d = new Date();
    public String time = format.format(d);
    public static int clientNumber = 0;
    public JFrame f = new JFrame("QQ MultiServer");
    public JTextArea show = new JTextArea(10,50);
    public JTextArea userinfo = new JTextArea(50,15);
    public JTextField porttext = new JTextField(10);
    public JButton start = new JButton("start");
    public JScrollPane jsp1 = new JScrollPane(show);
    public JScrollPane jsp2 = new JScrollPane(userinfo);
    public JPanel leftPanel = new JPanel(new BorderLayout());
    public JPanel rightPanel = new JPanel(new BorderLayout()); 
    public JPanel northPanel = new JPanel(new BorderLayout());
    public static boolean isStart = false;
    public String inputLine;
    public static ServerSocket serverSocket = null;
    public boolean listening = true;
    
    public static void main(String[] args) throws IOException{
        MultiTalkServer mts = new MultiTalkServer();
        mts.ui(mts);
    }
    
    public void ui(MultiTalkServer mts) {
        northPanel.setBorder(new TitledBorder("start server")); 
        northPanel.add(new JLabel("port: "),"West");
        northPanel.add(porttext, "Center");
        northPanel.add(start, "East");
        leftPanel.setBorder(new TitledBorder("server log")); 
        leftPanel.add(jsp2, "Center");
        rightPanel.setBorder(new TitledBorder("message")); 
        rightPanel.add(jsp1, "Center");
        show.setEditable(false);
        userinfo.setEditable(false);
        f.setSize(600,550);
        f.setLocation(500, 100);
        f.setLayout(new BorderLayout());
        f.add(northPanel, "North");
        f.add(rightPanel, "Center");  
        f.add(leftPanel, "West");
        f.setBackground(Color.GRAY);
        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);
        start.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {                   
                int port;  
                try {    
                    try {  
                        port = Integer.parseInt(porttext.getText());  
                    } catch (Exception e1) {  
                        throw new Exception("端口号为正整数!");  
                    }
                    if (port <= 0) {  
                        throw new Exception("端口号 为正整数!");  
                    }  
                    serverStart(port,mts);//启动服务器                         
                } catch (Exception exc) {  
                    JOptionPane.showMessageDialog(f, exc.getMessage(),"ERROR", JOptionPane.ERROR_MESSAGE);  
                }  
            }  
        });
    }
    
    public void serverStart(int port,MultiTalkServer mts) throws IOException,BindException
    {
        try {
            serverSocket = new ServerSocket(port);
            ServerThread serverthread=new ServerThread(serverSocket,mts);
            Thread t = new Thread(serverthread);
            t.start();//启动服务器线程
            isStart = true;
            userinfo.append("服务器已成功启动!" + "\n端口为" + port + "\n");
            start.setEnabled(false);    
            porttext.setEnabled(false);
        } catch (BindException e) {  
            isStart = false;  
            throw new BindException("The port number is occupied, please change new one!");  
        } catch (IOException e) {
            throw new IOException("Could not listen on port.");
            //System.exit(-1);
        } 
    }
}

//服务器线程
class ServerThread implements Runnable {
    MultiTalkServer mts1;
    public ServerSocket serverSocket;
    public ServerThread(ServerSocket serverSocket,MultiTalkServer mts) {  
      this.serverSocket = serverSocket;
      this.mts1=mts;
  }
    public void run(){
      mts1.userinfo.append("服务器启动时间: "+"\n"+ mts1.time  + '\n');
      while (mts1.listening)
      {
          Socket socket = null;
          try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "IOException!");
                e.printStackTrace();
            }  
          //程序将在此等候客户端的连接
          MultiTalkServer.clientNumber++;
          InetAddress inetAddress = socket.getInetAddress();
          mts1.userinfo.append(" Client " + MultiTalkServer.clientNumber + '\n');
          mts1.userinfo.append(" Host name is " + inetAddress.getHostName() + '\n');
          mts1.userinfo.append(" IP Address is " + inetAddress.getHostAddress() + '\n');
          MultiTalkServerThread client=new MultiTalkServerThread(socket,mts1);
          mts1.clients.add(client);
          client.start();
      }
      try {
            serverSocket.close();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "IOException!");
            e.printStackTrace();
        } 
    }
    }

class MultiTalkServerThread extends Thread
{
    MultiTalkServer mts=new MultiTalkServer();
    private Socket socket = null;
    MultiTalkServerThread c = null;
    String fromClient=null;
    PrintWriter out;
    BufferedReader in;
    boolean talking=true;
    public MultiTalkServerThread(Socket socket,MultiTalkServer mts1)
    {
        super("MultiTalkServerThread");
        this.socket = socket;
        mts=mts1;
        mts.show.setText("Accept OK!"+"\n");
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true); 
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "IOException!");
            e.printStackTrace();
        }
    }

    public void sentAll(String str) throws IOException {
        // Send sentence back to the client
        out.println(str);
    }
    public void run()
    {
        try{
            while( talking )
            {
                fromClient = in.readLine();
                // Send sentence back to the client
                for (int i = 0; i < mts.clients.size(); i++) {
                    c=mts.clients.get(i);
                    c.sentAll(fromClient);//将客户端内容发回客户端
                }
                mts.show.append(" " + mts.time + "\n");
                mts.show.append(" " + fromClient + '\n');
                if(mts.clients.size()==0)//当没有客户时服务器停止
                {
                    talking=false;                
                }
            }
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            MultiTalkServer.clientNumber--;
            if (MultiTalkServer.clientNumber == 0) {
                mts.userinfo.append("无客户端连接!" + "\n");
                //mts.clients.remove(c); // 防止新用户使用
            }
            else {
                mts.userinfo.append(" 退出一用户! 剩余用户: " + MultiTalkServer.clientNumber  + "\n");
            }
        }
    }
}
View Code

客户端:

package talktest;
import java.io.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class SingleTalkClient implements ActionListener
{
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date= new Date();
    String Name;
    String time = format.format(date);
    JFrame f=new JFrame("QQ Client");
    JButton b=new JButton("sending");
    JTextArea show=new JTextArea(10,50);
    JTextField send=new JTextField(50);
    JTextField username=new JTextField(10);
    JScrollPane jsp1=new JScrollPane(show);
    JPanel southPanel=new JPanel(new BorderLayout());
    JPanel northPanel=new JPanel(new BorderLayout()); 
    JPanel northPanel2=new JPanel(new BorderLayout()) ;
    String fromServer, fromUser;
    boolean sbye = false;
    boolean ubye = false;
    boolean talking = true;
    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(username.getText().equals("")){
                    JOptionPane.showMessageDialog(null, "用户名不能为空");
                }
                else{
                    Name=username.getText().trim();
                    fromUser=send.getText().trim();
                    fromUser= Name + ": " +fromUser ;
                    out.println(fromUser);
                    send.setText("");
                }
            }
        }
    }
    public void fun()throws IOException{
        f.setTitle("QQ client: "+username.getText());
        northPanel.setBorder(new TitledBorder("message")); 
        northPanel.add(jsp1, "Center");
        southPanel.setBorder(new TitledBorder("write"));  
        southPanel.add(send, "Center");  
        southPanel.add(b,"East");
        northPanel2.setBorder(new TitledBorder("username")); 
        northPanel2.add(username, "Center");
        show.setEditable(false);
        f.setSize(600,550);
        f.setLayout(new BorderLayout());  
        f.add(northPanel, "Center");  
        f.add(southPanel, "South"); 
        f.add(northPanel2, "North");
          f.setBackground(Color.GRAY);
        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(username.getText().equals("")){
                            JOptionPane.showMessageDialog(null, "用户名不能为空");
                        }
                        else{
                            Name=username.getText().trim();
                            fromUser=send.getText().trim();
                            fromUser= Name + ": " +fromUser ;
                            out.println(fromUser);//send massage to Server
                            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) {
            JOptionPane.showMessageDialog(null, "Don't know about host: 127.0.0.1.");
            //System.exit(1);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Couldn't get I/O for the connection to: 127.0.0.1.");
            //System.exit(1);
        }    
        record="";
        send.setText("");
        while( talking )  
        {
            fromServer=in.readLine();
            if(fromServer!=null){
                show.append(" " + time + "\n");
                show.append(fromServer+"\n");
            }
        }
        in.close();
        out.close();
        client.close();
    }
    public static void main(String[] args) throws IOException
    {
        new SingleTalkClient().fun();
        
    }
}
View Code

 

posted @ 2017-04-16 21:40  奇热行  阅读(303)  评论(0)    收藏  举报