zoukankan      html  css  js  c++  java
  • 聊天室设计

    JAVA的课程设计选择的聊天室,最开始不会写,完全没思路,然后去看了一下有关线程的一些知识,最后也是结合了一些人的想法写出来的聊天室。

    如果服务器放在本地电脑的话,有可能会客户端在别的电脑上运行不了,主要原因就是因为连不上服务器。我个人觉得可能是与防火墙这些有关系。可以在服务器上运行这个服务器,然后可以连接。

      1     package Chat;
      2 /**
      3  * 服务器端
      4  * @author opc
      5  */
      6 import java.io.DataInputStream;
      7 import java.io.DataOutputStream;
      8 import java.io.IOException;
      9 import java.net.ServerSocket;
     10 import java.net.Socket;
     11 import java.text.SimpleDateFormat;
     12 import java.util.ArrayList;
     13 import java.util.Date;
     14 import java.util.List;
     15 
     16 public class Server {
     17     private List<MyChannel> all = new ArrayList<MyChannel>();
     18     private ServerSocket server;
     19     int i = 0;
     20 
     21     public static void main(String args[]) throws IOException {
     22         new Server().start();
     23     }
     24 
     25     public void start() throws IOException {
     26         server = new ServerSocket(9450);
     27         while (true) {
     28             Socket client = server.accept();
     29             MyChannel channel = new MyChannel(client);
     30             all.add(channel); // 统一管理
     31             new Thread(channel).start();
     32         }
     33     }
     34 
     35     /**
     36      * 一个客户端就是一个通道
     37      * 
     38      * @author opc
     39      *
     40      */
     41 
     42     private class MyChannel implements Runnable {
     43         private DataInputStream dis;
     44         private DataOutputStream dos;
     45         private boolean isRunning = true;
     46         private String name;
     47         public MyChannel(Socket client) {
     48             try {
     49                 dis = new DataInputStream(client.getInputStream());
     50                 dos = new DataOutputStream(client.getOutputStream());
     51                 this.name = dis.readUTF();
     52                 
     53             } catch (IOException e) {
     54                 Closeutil.ColseAll(dis, dos);
     55                 isRunning = false;
     56             }
     57         }
     58         /**
     59          *  接受数据
     60          * @return
     61          */
     62         
     63         private String receive() {
     64             String meg = "";
     65             try {
     66                 meg = dis.readUTF();
     67             } catch (IOException e) {
     68                 Closeutil.ColseAll(dis, dos);
     69                 isRunning = false;
     70                 all.remove(this);
     71             }
     72             return meg;
     73         }
     74 
     75         /**
     76          * 
     77          * 发送数据
     78          * 
     79          */
     80 
     81         private void send(String meg) {
     82             if (null == meg || meg.equals("")) {
     83                 return;
     84             }
     85             try {
     86                 dos.writeUTF(meg);
     87                 dos.flush();
     88             } catch (IOException e) {
     89                 Closeutil.ColseAll(dis, dos);
     90                 isRunning = false;
     91                 all.remove(this);
     92             }
     93         }
     94         
     95         /*
     96          * 发送给其他客户端
     97          */
     98 
     99         private void sendOthers(String meg) {
    100             SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss");
    101             int loc = meg.indexOf(":");
    102         //    System.out.println(loc+"   "+meg.length()+"  "+meg);
    103             if(meg.charAt(loc+1)=='@'){
    104                 /**
    105                  * 私聊
    106                  */
    107                 String send_name = meg.substring(0,loc);
    108                 String name = meg.substring(loc+2,meg.indexOf(":",loc+1));
    109                 String content = meg.substring(meg.indexOf(":",loc+1)+1);
    110                 for(MyChannel other:all){
    111                     if(other.name.equals(name)){
    112                         other.send(this.name+df.format(new Date())+"悄悄对你说 :  "+content+'
    ');
    113                     }else if(other.name.equals(send_name)){
    114                         other.send(this.name+df.format(new Date())+"对 "+name+" 悄悄说:   "+content+'
    ');
    115                     }
    116                 }
    117             }else{
    118                 // 遍历容器,群聊
    119                 String sendname = meg.substring(0,meg.indexOf(":"));
    120                 String content = meg.substring(meg.indexOf(":")+1);
    121                 for (MyChannel other : all) {
    122                     other.send(sendname+"  "+df.format(new Date())+" : "+content+'
    ');
    123                 }
    124             }
    125         }
    126 
    127         public void run() {
    128             while (isRunning) {
    129                 sendOthers(receive());
    130             }
    131 
    132         }
    133     }
    134 }
    Server
     1 package Chat;
     2 
     3 import java.io.IOException;
     4 import java.net.Socket;
     5 import java.net.UnknownHostException;
     6 
     7 
     8 
     9 /**
    10  * 客户端
    11  * @author opc
    12  *
    13  */
    14 
    15 public class Client {
    16     public static void main(String[] args) throws UnknownHostException, IOException {
    17         Socket client;
    18         Gird grid = new Gird();
    19         client = grid.getClient();
    20         Listenner listener = new Listenner();  
    21         grid.setMycommandListenner(listener);
    22         new Thread(new Receive(client,grid)).start();
    23     }
    24 }
    Client
     1 package Chat;
     2 
     3 import java.io.Closeable;
     4 
     5 
     6 /**
     7  * 关闭流的方法
     8  * @author opc
     9  *
    10  */
    11 public class Closeutil {
    12     public static void ColseAll(Closeable...io){
    13         for(Closeable temp:io){
    14             try{
    15                 if(temp!=null){
    16                     temp.close();
    17                 }
    18             }catch(Exception e){
    19                 
    20             }
    21         }
    22     }
    23 }
    closeutill
      1 package Chat;
      2 
      3 import java.awt.BorderLayout;
      4 import java.awt.Dimension;
      5 import java.awt.GridLayout;
      6 import java.awt.Toolkit;
      7 import java.io.IOException;
      8 import java.net.Socket;
      9 import java.net.UnknownHostException;
     10 
     11 import javax.swing.JButton;
     12 import javax.swing.JFrame;
     13 import javax.swing.JLabel;
     14 import javax.swing.JPanel;
     15 import javax.swing.JScrollPane;
     16 import javax.swing.JSplitPane;
     17 import javax.swing.JTextArea;
     18 import javax.swing.JTextField;
     19 import javax.swing.border.TitledBorder;;
     20 
     21 @SuppressWarnings("serial")
     22 public class Gird extends JFrame{
     23     private JTextField name;  //姓名输入框
     24     private Socket client;    
     25     private JPanel TopFloor;  //顶层容器
     26     private JPanel LowFloor;  //底层容器
     27     private JTextArea TextArea;   //显示字体界面
     28     private JTextField TextFile;
     29     private JTextField TextIp;
     30     private JButton But_Send;    //发送按钮
     31     private JButton But_Name;    //确认按钮
     32     private JScrollPane rightScroll;    
     33     private JScrollPane leftScroll;
     34     private JSplitPane centerSplit;    
     35     @SuppressWarnings("unused")
     36     private MycommandListenner listener;    
     37     Gird() throws UnknownHostException, IOException{
     38         But_Send = new JButton("发送");
     39         But_Name = new JButton("确认");
     40         name = new JTextField(10);
     41         TextIp = new JTextField("118.89.51.123");
     42         TextFile = new JTextField();
     43         TextArea = new JTextArea();
     44         TopFloor = new JPanel();
     45         //this.client = client;
     46         client = new Socket(TextIp.getText(),3390);
     47         TopFloor.setLayout(new GridLayout(1,7));
     48         TopFloor.add(new JLabel("      姓名"));
     49         TopFloor.add(name);
     50         TopFloor.add(But_Name);
     51         TopFloor.add(new JLabel("           Ip"));
     52         TopFloor.add(new JLabel("  118.89.51.123"));
     53         rightScroll = new JScrollPane(TextArea);
     54         rightScroll.setBorder(new TitledBorder("消息框"));
     55         LowFloor = new JPanel(new BorderLayout());
     56         LowFloor.add(TextFile,"Center");
     57         LowFloor.add(But_Send,"East");
     58         LowFloor.setBorder(new TitledBorder("写消息"));
     59         centerSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftScroll,rightScroll);
     60         setTitle("聊天室");
     61         setLayout(new BorderLayout());
     62         add(TopFloor,"North");
     63         add(centerSplit,"Center");
     64         add(LowFloor,"South");
     65         Toolkit kit = Toolkit.getDefaultToolkit();
     66         Dimension screensize = kit.getScreenSize();
     67         int screenHeight = screensize.height;
     68         int screenWhdth = screensize.width;
     69         setBounds(400,200,screenWhdth/2,screenHeight/2);
     70         setVisible(true);
     71         setDefaultCloseOperation(EXIT_ON_CLOSE);
     72     }
     73     /**
     74      * 获取姓名
     75      * @return
     76      */
     77     public String getname(){
     78         return name.getText();
     79     }
     80     /**
     81      * 添加监听
     82      * @param listener
     83      */
     84     void setMycommandListenner(MycommandListenner listener){
     85         this.listener = listener;
     86         listener.setJTextField(TextFile);
     87         listener.setJtextArea(TextArea);
     88         listener.set(client);
     89         listener.settextname(name);
     90         But_Name.addActionListener(listener);
     91         TextFile.addActionListener(listener);
     92         But_Send.addActionListener(listener);
     93     }
     94     
     95     public Socket getClient(){
     96         return client;
     97     }
     98     /**
     99      * 显示界面
    100      * @param meg
    101      */
    102     public void show(String meg){
    103         TextArea.append(meg);
    104     }
    105     /**
    106      * 获取输入框中的文字
    107      * @return
    108      */
    109     public String getText(){
    110         return TextFile.getText();
    111     }
    112 }
    Grid
     1 package Chat;
     2 
     3 import java.awt.event.ActionEvent;
     4 import java.io.DataOutputStream;
     5 import java.io.IOException;
     6 import java.net.Socket;
     7 
     8 import javax.swing.JTextArea;
     9 import javax.swing.JTextField;
    10 
    11 public class Listenner implements MycommandListenner {
    12     JTextArea textShow;
    13     JTextField textInput;
    14     JTextField textname;
    15     private DataOutputStream dos;
    16     Socket client;
    17     private String name;
    18     /**
    19      * 进行监听
    20      */
    21     public void actionPerformed(ActionEvent e) {
    22         if(e.getActionCommand().equals("确认")){
    23             this.setName(textname.getText());
    24             send(name);
    25             System.out.println(e.getActionCommand().toString());
    26         }else {            
    27             String meg = textInput.getText();
    28             send(name+":"+meg);
    29             //textShow.append(meg+'
    ');
    30             textInput.setText("");
    31         }
    32     }
    33     /**
    34      * 设置socket
    35      */
    36     public void set(Socket client){
    37         this.client = client;
    38         try {
    39             dos = new DataOutputStream(client.getOutputStream());
    40         } catch (IOException e) {
    41             e.printStackTrace();
    42         }
    43     }
    44     /**
    45      * 设置名字
    46      */
    47     public void setName(String name){
    48         this.name = name;
    49     }
    50     @Override
    51     /**
    52      * 设置输入框
    53      */
    54     public void setJTextField(JTextField text) {
    55         textInput = text;
    56     }
    57     @Override
    58     /**
    59      * 设置屏幕的字
    60      */
    61     public void setJtextArea(JTextArea area) {
    62         textShow = area;
    63     }
    64     /**
    65      * 设置名字
    66      */
    67     public void settextname(JTextField text){
    68         textname = text;
    69     }
    70     /**
    71      * 发送消息
    72      * @param meg
    73      */
    74     public void send(String meg){
    75         if(!meg.equals("")){
    76             try {
    77                 dos.writeUTF(meg);
    78                 dos.flush();
    79             } catch (IOException e) {
    80                 Closeutil.ColseAll(dos);
    81             }
    82         }
    83     }
    84 }
    Listenner
     1 package Chat;
     2 /**
     3  * 一个监听的接口
     4  */
     5 import java.awt.event.ActionListener;
     6 import java.net.Socket;
     7 import javax.swing.JTextArea;
     8 import javax.swing.JTextField;
     9 
    10 interface MycommandListenner extends ActionListener{
    11     
    12     public void setJTextField(JTextField text);
    13     public void setJtextArea(JTextArea area);
    14     public void set(Socket client);
    15     public void setName(String name);
    16     public void settextname(JTextField text);
    17 
    18 }
    MycommandListenner
     1 package Chat;
     2 /**
     3  * 用于客户端的信息接受
     4  * 
     5  * @author opc
     6  */
     7 import java.io.DataInputStream;
     8 import java.io.IOException;
     9 import java.net.Socket;
    10 
    11 public class Receive implements Runnable {
    12     /**
    13      * 接受流
    14      */
    15     private DataInputStream dis;
    16     Gird grid;
    17     /**
    18      * 判断运行的标志
    19      */
    20     private boolean isRunning = true;
    21     public Receive() {
    22         
    23     }
    24     /**
    25      * 构造方法
    26      * @param client
    27      * @param grid
    28      */
    29     public Receive(Socket client,Gird grid){
    30         try {
    31             dis = new DataInputStream(client.getInputStream());
    32             this.grid = grid;
    33         } catch (IOException e) {
    34             isRunning = false;
    35             Closeutil.ColseAll(dis);
    36         }
    37     }
    38     /**
    39      * 接收数据
    40      * @return
    41      */
    42     public String receive(){
    43         String meg = "";
    44         try {
    45             meg = dis.readUTF();
    46         } catch (IOException e) {
    47             isRunning = false;
    48             Closeutil.ColseAll(dis);
    49         }
    50         return meg;
    51     }
    52     
    53     @Override
    54     /**
    55      * 重写run方法
    56      */
    57     public void run() {
    58         while(isRunning){
    59             grid.show(receive());
    60         }
    61     }
    62     
    63 }
    Receive
  • 相关阅读:
    Linux 学习笔记1
    Openstack中的LoadBalancer(负载均衡)功能使用实例
    分析事务与锁3
    MemoryStream
    JBPM4学习之路2:流程部署
    在MongoDB中一起使用$or和sort()
    使用avalon msui绑定实现基于组件的开发
    深度剖析Byteart Retail案例:应用程序的配置
    最年轻的系统分析员的考试心得
    linux学习体会,献给初学者
  • 原文地址:https://www.cnblogs.com/Tree-dream/p/6251590.html
Copyright © 2011-2022 走看看