java socket/swing聊天系统

3 篇文章 0 订阅
0 篇文章 0 订阅
上个周五的下午,在公司闲来无事,
写了个小程序玩玩,
稍微测试了一下,居然能用!
但由于代码量较少,也谈不上什么设计,
发上来算是个备忘吧:
服务器端程序:
  1. package com.test.talk;
  2. import java.awt.BorderLayout;
  3. import java.awt.FlowLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import java.awt.event.WindowAdapter;
  7. import java.awt.event.WindowEvent;
  8. import java.io.DataInputStream;
  9. import java.io.DataOutputStream;
  10. import java.io.IOException;
  11. import java.net.BindException;
  12. import java.net.ServerSocket;
  13. import java.net.Socket;
  14. import java.util.LinkedList;
  15. import java.util.List;
  16. import javax.swing.JButton;
  17. import javax.swing.JFrame;
  18. import javax.swing.JLabel;
  19. import javax.swing.JPanel;
  20. import javax.swing.JTextField;
  21. public class Server extends JFrame
  22. {
  23.     boolean started = false;
  24.     private ServerSocket ss = null;
  25.     private List clientList = new LinkedList();
  26.     private JLabel portLbl = null;
  27.     private JTextField portTxt = null;
  28.     private JButton portSetBtn = null;
  29.     private String port = null;
  30.     private JButton startBtn = null;
  31.     private JButton stopBtn = null;
  32.     private JPanel mainPanle = null;
  33.     private JPanel headPanle = null;
  34.     public static void main(String[] args)
  35.     {
  36.         new Server();
  37.     }
  38.     public Server()
  39.     {
  40.         headPanle = new JPanel(new FlowLayout(FlowLayout.LEFT));
  41.         portLbl = new JLabel("PORT");
  42.         portTxt = new JTextField(7);
  43.         portSetBtn = new JButton("OK");
  44.         portSetBtn.addActionListener(new ActionListener()
  45.         {
  46.             public void actionPerformed(ActionEvent e)
  47.             {
  48.                 if (portTxt.getText().matches("//d+"))
  49.                 {
  50.                     port = portTxt.getText();
  51.                     startBtn.setEnabled(true);
  52.                     stopBtn.setEnabled(true);
  53.                 }
  54.                 else
  55.                 {
  56.                     javax.swing.JOptionPane.showMessageDialog(null"port be inputted is illegal");
  57.                 }
  58.             }
  59.         });
  60.         headPanle.add(portLbl);
  61.         headPanle.add(portTxt);
  62.         headPanle.add(portSetBtn);
  63.         getContentPane().add(headPanle, BorderLayout.NORTH);
  64.         startBtn = new JButton("Start");
  65.         stopBtn = new JButton("Stop");
  66.         startBtn.setEnabled(false);
  67.         stopBtn.setEnabled(false);
  68.         mainPanle = new JPanel(new FlowLayout(FlowLayout.CENTER));
  69.         startBtn.addActionListener(new StartClickListener());
  70.         stopBtn.addActionListener(new ActionListener()
  71.         {
  72.             public void actionPerformed(ActionEvent e)
  73.             {
  74.                 started = false;
  75.                 clientList.clear();
  76.                 try
  77.                 {
  78.                     if (ss != null)
  79.                     {
  80.                         ss.close();
  81.                     }
  82.                 }
  83.                 catch(IOException e1)
  84.                 {
  85.                     e1.printStackTrace();
  86.                 }
  87.             }
  88.         });
  89.         mainPanle.add(startBtn);
  90.         mainPanle.add(stopBtn);
  91.         getContentPane().add(mainPanle, BorderLayout.CENTER);
  92.         addWindowListener(new WindowAdapter()
  93.         {
  94.             public void windowClosing(WindowEvent e)
  95.             {
  96.                 started = false;
  97.                 clientList.clear();
  98.                 try
  99.                 {
  100.                     if (ss != null)
  101.                     {
  102.                         ss.close();
  103.                     }
  104.                 }
  105.                 catch(IOException e1)
  106.                 {
  107.                     e1.printStackTrace();
  108.                 }
  109.                 System.exit(0);
  110.             }
  111.         });
  112.         this.setSize(300, 300);
  113.         setLocation(100, 100);
  114.         pack();
  115.         setVisible(true);
  116.     }
  117.     private void start()
  118.     {
  119.         try
  120.         {
  121.             ss = new ServerSocket(Integer.parseInt(port));
  122.             started = true;
  123.         }
  124.         catch(BindException be)
  125.         {
  126.             javax.swing.JOptionPane.showMessageDialog(null"port is useing by others");
  127.         }
  128.         catch(IOException e)
  129.         {
  130.             javax.swing.JOptionPane.showMessageDialog(null"connect server fail");
  131.         }
  132.         try
  133.         {
  134.             while(started)
  135.             {
  136.                 Socket s = ss.accept();
  137.                 ClientImpl cr = new ClientImpl(s);
  138.                 new Thread(cr).start();
  139.                 clientList.add(cr);
  140.                 System.out.println("System Info:" + s.getInetAddress() + "connect successfully");
  141.             }
  142.         }
  143.         catch(IOException e)
  144.         {
  145.             System.out.println("Client closed!");
  146.         }
  147.     }
  148.     class ClientImpl implements Runnable
  149.     {
  150.         private Socket s;
  151.         private DataInputStream dis = null;
  152.         private DataOutputStream dos = null;
  153.         boolean bConnect = false;
  154.         public ClientImpl(Socket s)
  155.         {
  156.             this.s = s;
  157.             try
  158.             {
  159.                 dis = new DataInputStream(s.getInputStream());
  160.                 dos = new DataOutputStream(s.getOutputStream());
  161.                 bConnect = true;
  162.             }
  163.             catch(IOException e)
  164.             {
  165.                 e.printStackTrace();
  166.             }
  167.         }
  168.         private void send(String str)
  169.         {
  170.             try
  171.             {
  172.                 dos.writeUTF(str);
  173.             }
  174.             catch(IOException e)
  175.             {
  176.                 e.printStackTrace();
  177.             }
  178.         }
  179.         public void run()
  180.         {
  181.             ClientImpl cr = null;
  182.             try
  183.             {
  184.                 while(bConnect)
  185.                 {
  186.                     String str = dis.readUTF();
  187.                     System.out.println(str);
  188.                     for(int i = 0; i < clientList.size(); i++)
  189.                     {
  190.                         cr = (ClientImpl) clientList.get(i);
  191.                         cr.send(str);
  192.                     }
  193.                 }
  194.             }
  195.             catch(Exception e)
  196.             {
  197.                 clientList.remove(cr);
  198.                 System.out.println(s.getInetAddress() + "has leaved");
  199.             }
  200.             finally
  201.             {
  202.                 try
  203.                 {
  204.                     if (dis != null)
  205.                         dis.close();
  206.                     if (dos != null)
  207.                         dos.close();
  208.                     if (s != null)
  209.                     {
  210.                         s.close();
  211.                         s = null;
  212.                     }
  213.                 }
  214.                 catch(IOException io)
  215.                 {
  216.                     io.printStackTrace();
  217.                 }
  218.             }
  219.         }
  220.     }
  221.     class StartClickListener implements Runnable, ActionListener
  222.     {
  223.         public void actionPerformed(ActionEvent e)
  224.         {
  225.             new Thread(this).start();
  226.         }
  227.         public void run()
  228.         {
  229.             start();
  230.         }
  231.     }
  232. }
客户端程序:
  1. package com.test.talk;
  2. import java.awt.BorderLayout;
  3. import java.awt.FlowLayout;
  4. import java.awt.event.ActionEvent;
  5. import java.awt.event.ActionListener;
  6. import java.awt.event.WindowAdapter;
  7. import java.awt.event.WindowEvent;
  8. import java.io.DataInputStream;
  9. import java.io.DataOutputStream;
  10. import java.io.IOException;
  11. import java.net.Socket;
  12. import java.net.UnknownHostException;
  13. import javax.swing.JButton;
  14. import javax.swing.JFrame;
  15. import javax.swing.JLabel;
  16. import javax.swing.JPanel;
  17. import javax.swing.JTextArea;
  18. import javax.swing.JTextField;
  19. /**
  20.  * Client
  21.  * 
  22.  * @author hx0272
  23.  * 
  24.  */
  25. public class Client
  26. {
  27.     public static void main(String[] args)
  28.     {
  29.         ClientFrame frame = new ClientFrame();
  30.     }
  31. }
  32. class ClientFrame extends JFrame
  33. {
  34.     private JPanel mainPanel;
  35.     private JPanel headPanel;
  36.     private JPanel footPanel;
  37.     private JTextArea showArea;
  38.     private JTextField inputTxt;
  39.     private JLabel portLbl;
  40.     private JLabel ipLbl;
  41.     private JLabel nameLbl;
  42.     private JTextField portTxt;
  43.     private JTextField ipTxt;
  44.     private JTextField nameTxt;
  45.     private JButton submitBtn;
  46.     private JButton nameBtn;
  47.     private JButton loginBtn;
  48.     private Socket clientSocket = null;
  49.     private DataOutputStream dos = null;
  50.     private DataInputStream dis = null;
  51.     private boolean bConnect = false;
  52.     private String name = "";
  53.     public ClientFrame()
  54.     {
  55.         init();
  56.     }
  57.     private void init()
  58.     {
  59.         //main panel Begin
  60.         mainPanel = new JPanel();
  61.         showArea = new JTextArea(15, 80);
  62.         showArea.setEditable(false);
  63.         mainPanel.add(showArea);
  64.         getContentPane().add(mainPanel, BorderLayout.CENTER);
  65.         //main panel End
  66.         //head panel Begin
  67.         headPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
  68.         portLbl = new JLabel("PORT");
  69.         portTxt = new JTextField(7);
  70.         ipLbl = new JLabel("IP");
  71.         ipTxt = new JTextField(25);
  72.         nameLbl = new JLabel("name");
  73.         nameTxt = new JTextField(15);
  74.         nameBtn = new JButton("OK");
  75.         loginBtn = new JButton("login");
  76.         nameBtn.addActionListener(new ActionListener()
  77.         {
  78.             public void actionPerformed(ActionEvent e)
  79.             {
  80.                 String tmp = nameTxt.getText();
  81.                 if (tmp != null || !tmp.equals(""))
  82.                 {
  83.                     int id = javax.swing.JOptionPane.showConfirmDialog(null"yes or no""choose yes",
  84.                             javax.swing.JOptionPane.OK_OPTION);
  85.                     if (id == 0)
  86.                     {
  87.                         name = nameTxt.getText();
  88.                         loginBtn.setEnabled(true);
  89.                         nameBtn.setEnabled(false);
  90.                     }
  91.                 }
  92.             }
  93.         });
  94.         headPanel.add(portLbl);
  95.         headPanel.add(portTxt);
  96.         headPanel.add(ipLbl);
  97.         headPanel.add(ipTxt);
  98.         headPanel.add(loginBtn);
  99.         headPanel.add(nameLbl);
  100.         headPanel.add(nameTxt);
  101.         headPanel.add(nameBtn);
  102.         loginBtn.setEnabled(false);
  103.         loginBtn.addActionListener(new ButtonClickAction());
  104.         getContentPane().add(headPanel, BorderLayout.NORTH);
  105.         //head panel End
  106.         //foot panel Begin
  107.         footPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
  108.         inputTxt = new JTextField(70);
  109.         submitBtn = new JButton("submit");
  110.         footPanel.add(inputTxt);
  111.         footPanel.add(submitBtn);
  112.         submitBtn.addActionListener(new ButtonClickAction());
  113.         submitBtn.setEnabled(false);
  114.         getContentPane().add(footPanel, BorderLayout.SOUTH);
  115.         //foot panel End
  116.         addWindowListener(new WindowAdapter()
  117.         {
  118.             public void windowClosing(WindowEvent e)
  119.             {
  120.                 disConnect();
  121.                 System.exit(0);
  122.             }
  123.         });
  124.         this.setSize(300, 300);
  125.         setLocation(100, 100);
  126.         pack();
  127.         setVisible(true);
  128.     }
  129.     /**
  130.      * login button / submit button action listener
  131.      * 
  132.      * @author hx0272
  133.      * 
  134.      */
  135.     class ButtonClickAction implements ActionListener
  136.     {
  137.         public void actionPerformed(ActionEvent e)
  138.         {
  139.             if ("submit".equals(e.getActionCommand()))
  140.             {
  141.                 String str = inputTxt.getText().trim();
  142.                 inputTxt.setText("");
  143.                 sendToServer(str);
  144.             }
  145.             else if ("login".equals(e.getActionCommand()))
  146.             {
  147.                 connect();
  148.             }
  149.         }
  150.     }
  151.     /**
  152.      * enter be inputted event
  153.      * 
  154.      * @author hx0272
  155.      */
  156.     class EnterClickAction implements ActionListener
  157.     {
  158.         public void actionPerformed(ActionEvent e)
  159.         {
  160.             String str = inputTxt.getText().trim();
  161.             inputTxt.setText("");
  162.             sendToServer(str);
  163.         }
  164.     }
  165.     /**
  166.      * send message to server
  167.      * 
  168.      * @author hx0272
  169.      */
  170.     private void sendToServer(String str)
  171.     {
  172.         try
  173.         {
  174.             dos.writeUTF(name + ":" + str);
  175.             dos.flush();
  176.         }
  177.         catch(IOException e)
  178.         {
  179.             e.printStackTrace();
  180.         }
  181.     }
  182.     /**
  183.      * close resource
  184.      * 
  185.      * @author hx0272
  186.      */
  187.     private void disConnect()
  188.     {
  189.         try
  190.         {
  191.             // clientSocket.close();
  192.             //          
  193.             // dos.close();
  194.             bConnect = false;
  195.         }
  196.         catch(Exception e)
  197.         {
  198.             e.printStackTrace();
  199.         }
  200.     }
  201.     /**
  202.      * receive message from server
  203.      * 
  204.      * @author hx0272
  205.      */
  206.     private class Receive implements Runnable
  207.     {
  208.         public void run()
  209.         {
  210.             try
  211.             {
  212.                 while(bConnect)
  213.                 {
  214.                     String str = dis.readUTF();
  215.                     showArea.setText(showArea.getText() + str + '/n');
  216.                 }
  217.             }
  218.             catch(IOException e)
  219.             {
  220.                 javax.swing.JOptionPane.showMessageDialog(null"connect server error");
  221.             }
  222.         }
  223.     }
  224.     /**
  225.      * connection begin
  226.      * 
  227.      * @author hx0272
  228.      */
  229.     private void connect()
  230.     {
  231.         try
  232.         {
  233.             if (ipTxt.getText().matches("//d{1,3}.//d{1,3}.//d{1,3}.//d{1,3}") && portTxt.getText().matches("//d+"))
  234.             {
  235.                 clientSocket = new Socket(ipTxt.getText(), Integer.parseInt(portTxt.getText()));
  236.                 dos = new DataOutputStream(clientSocket.getOutputStream());
  237.                 dis = new DataInputStream(clientSocket.getInputStream());
  238.                 bConnect = true;
  239.                 new Thread(new Receive()).start();
  240.                 System.out.println("I am coming");
  241.                 javax.swing.JOptionPane.showMessageDialog(null"connect server success");
  242.                 submitBtn.setEnabled(true);
  243.                 inputTxt.addActionListener(new EnterClickAction());
  244.             }
  245.             else
  246.             {
  247.                 javax.swing.JOptionPane.showMessageDialog(null"port or ip be inputted is illegal");
  248.             }
  249.         }
  250.         catch(UnknownHostException uhe)
  251.         {
  252.             javax.swing.JOptionPane.showMessageDialog(null"connect server error");
  253.         }
  254.         catch(IOException e)
  255.         {
  256.             javax.swing.JOptionPane.showMessageDialog(null"connect server error");
  257.         }
  258.     }
  259. }
使用说明:
1.先运行服务器端程序,设定好端口号
2.点击Start按钮,运行服务器
3.运行客户端程序
4.设定好昵称
5.设定与服务器端匹配的端口号和服务器的ip地址
6.点击Login按钮,登录到聊天系统
7.可以聊天了。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值