java Socket实现简单聊天室

这几天重拾java,整理资料正好发现3年前,用java写的一个很low 的聊天室,还是跟大家分享一下吧,自己也回顾回顾。
LoginFrame.java

package com.java;


import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;

public class LoginFrame extends JFrame implements ActionListener
{
    JPanel          contentPane;
    JLabel          jLabel1=new JLabel();
    JTextField      jTextField1=new JTextField();
    ButtonGroup     buttonGroup1=new ButtonGroup();
    JRadioButton    jRadioButton1=new JRadioButton("男");
    JRadioButton    jRadioButton2=new JRadioButton("女");
    JLabel          jLabel2=new JLabel("性别");
    JButton         jButton1=new JButton();
    JButton         jButton2=new JButton(); 
    String          sex="男";
    String          name=null;
    boolean         bool=false;
    Socket          socket;
    DataInputStream  in;
    DataOutputStream  out;

    public LoginFrame()
    {
        setSize(new Dimension(400,210));
        setTitle("登录界面");
        setVisible(true);
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(null);
        this.setResizable(false);
        jLabel1.setFont(new Font("Dialog",15,15));
        jLabel1.setText("请输入您的昵称");
        jLabel1.setBounds(53,20,113,44);
        jTextField1.setBounds(182,25,154,33);
        jRadioButton1.setFont(new Font("Dialog",Font.PLAIN,13));
        jRadioButton1.setSelected(true);
        jRadioButton1.setBounds(186,64,91,25);
        jRadioButton1.addActionListener(this);
        jRadioButton2.setFont(new Font("Dialog",Font.PLAIN,13));
        jRadioButton2.setBounds(187,90,91,25);
        jRadioButton2.addActionListener(this);
        jLabel2.setFont(new Font("Dialog",Font.PLAIN,15));
        jLabel2.setBounds(136,80,34,16);
        jButton1.setBounds(182,138,71,25);
        jButton1.setText("确定");
        jButton1.addActionListener(this);
        jButton2.setBounds(264,138,71,25);
        jButton2.setText("取消");
        jButton2.addActionListener(this);
        contentPane.add(jLabel1);
        contentPane.add(jTextField1);
        contentPane.add(jRadioButton1);
        contentPane.add(jRadioButton2);
        contentPane.add(jLabel2);
        contentPane.add(jButton2);
        contentPane.add(jButton1);
        buttonGroup1.add(jRadioButton1);
        buttonGroup1.add(jRadioButton2);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = getSize();
        if(frameSize.height>screenSize.height)
        {
            frameSize.height=screenSize.height;
        }
        if(frameSize.width>screenSize.width)
        {
            frameSize.width=screenSize.width;
        }
        setLocation((screenSize.width - frameSize.width)/2,(screenSize.height - frameSize.height)/2);
        setVisible(true);
    }
    public void setClection(Socket soc,DataInputStream din,DataOutputStream dout)
    {
        socket=soc;
        in=din;
        out=dout;
    }
    public String getName()
    {
        return name;
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == jRadioButton1)  sex="男";
        if(e.getSource() == jRadioButton2)  sex="女";
        if(e.getSource() == jButton2)  jTextField1.setText("");
        else if(e.getSource() == jButton1)
        {
            if(jTextField1.getText().equals(""))
            {
                jTextField1.setText("请输入昵称");
                return;
            }
            name=jTextField1.getText();
            try{
                out.writeUTF("新用户:"+name+"/"+sex);
            }catch(Exception ee){ return; }
        }
    }
}

chatFrame.java

package com.java;

import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;

public class chatFrame extends JFrame implements ActionListener,Runnable
{
    LoginFrame frame=new LoginFrame();
    Thread thread;
    JPanel contentPane;
    JScrollPane jScrollPane1=new JScrollPane();
    JScrollPane jScrollPane2=new JScrollPane();
    JButton jBtnSend = new JButton("发送");
    JButton jBtnClear = new JButton("清空");
    JTextArea jTextArea1=new JTextArea();
    JTextArea jTextArea2=new JTextArea();
    JScrollPane jScrollPane3=new JScrollPane();
    JList jList1 = new JList();
    Socket socket;
    int port =10000;
    DataInputStream in;
    DataOutputStream out;
    Vector vector=new Vector();
    String chatstr,str;

    public chatFrame()
    {
        setTitle("思维聊天室");
        setSize(602,515);
        this.setResizable(false);
        this.setVisible(false);
        try{
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          addWindowListener (new WindowAdapter()
          {
            public void windowClosing(WindowEvent e)
            {
                try{
                    out.writeUTF("下线了:"+frame.name+"/"+frame.sex);
                    out.close();
                    in.close();
                    socket.close();
                }catch(Exception ee){  }
                finally
                {
                    frame.dispose();
                    dispose();

                }
            }
          }
         );
        jbInit();

    }catch(Exception exception)
    { exception.printStackTrace();}

   }
   void jbInit() throws Exception
   {
       frame.setVisible(true);
       jScrollPane1.setBounds(2,2,445,320);
       jScrollPane2.setBounds(1,333,448,95);
       jScrollPane3.setBounds(458,6,139,424);
       jBtnSend.setBounds(93,441,78,31);
       jBtnClear.setBounds(185,441,76,31);
       jTextArea1.setEditable(false);
       contentPane = (JPanel)getContentPane();
       contentPane.setLayout(null);
       contentPane.add(jScrollPane2);
       contentPane.add(jScrollPane1,null);
       contentPane.add(jScrollPane3);
       contentPane.add(jBtnSend);
       contentPane.add(jBtnClear);
       jScrollPane1.getViewport().add(jTextArea1);
       jScrollPane2.getViewport().add(jTextArea2);
       jScrollPane3.getViewport().add(jList1);
       jBtnClear.addActionListener(this);
       jBtnSend.addActionListener(this);
       try{
           InetAddress address=InetAddress.getLocalHost();
           socket=new Socket(address.getHostAddress(),port);
           in=new DataInputStream(socket.getInputStream());
           out=new DataOutputStream(socket.getOutputStream());

       }catch(Exception e){
           setVisible(true);
           jTextArea2.setText("无法与服务器连接,请退出....");

       }
       if(thread == null)
       {
           thread=new Thread(this);
           thread.start();
       }
       frame.setClection(socket,in,out);
     }
    public void actionPerformed(ActionEvent e)
    {
     if(e.getSource()==jBtnSend)
     { sendStr();}
     if(e.getSource()==jBtnClear)
     { jTextArea1.setText("");}
    }
    public void sendStr()
    {
        chatstr = jTextArea2.getText();
        if(chatstr.equals(""))
        {
            jTextArea2.setText("please say a word:");
            return;
        }
        try{
            out.writeUTF(frame.name + ":"+chatstr);
            jTextArea2.setText("");
        }catch(Exception ee) {  }

    }
    public void run()
    {
        String sl=null;
        String ss=null;
        String s=null;
        while(true)
        {
            try
            {
                sl=in.readUTF();
            }catch(Exception ee)
            {
                vector.removeAllElements();
                jList1.setListData(vector);
                jTextArea2.setText("已经与服务器断开...");
                return;

            }
            if(sl.startsWith("可以注册"))
            {
                frame.setVisible(false);
                setVisible(true);
                setTitle("昵称..."+frame.getName());
                continue;
            }
            else if(sl.startsWith("该用户名已注册"))
            {
                frame.jTextField1.setText("请重新输入昵称");
                continue;
            }
            else if(sl.startsWith("新用户"))
            {
                StringTokenizer st=new StringTokenizer(sl,":");
                ss=null;
                s=null;
                ss=st.nextToken();
                s=st.nextToken();
                vector.addElement(s);
                jList1.setListData(vector);
                continue;
            }
            else if(sl.startsWith("下线了"))
            {
                StringTokenizer st=new StringTokenizer(sl,":");
                ss=null;
                s=null;
                ss=st.nextToken();
                s=st.nextToken();
                vector.removeElement(s);
                jList1.setListData(vector);
                continue;
            }
            jTextArea1.append(sl+"\n");

        }
    }
}

chat.java

package com.java;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Chat{
    boolean  packFrame=false;
    Chat(){
        chatFrame frame=new chatFrame();
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize=frame.getSize();
        if(frameSize.height>screenSize.height)
        {
            frameSize.height=screenSize.height;
        }
        if(frameSize.width>screenSize.width)
        {
            frameSize.width=screenSize.width;
        }
        frame.setLocation((screenSize.width - frameSize.width)/2,(screenSize.height - frameSize.height)/2);
    }
public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            new Chat();}
    });
  }
}

Server.java

package com.java;


import java.io.*;
import java.net.*;
import java.util.*;

public class Server extends ServerSocket
{
   static final int SERVER_PORT=10000;
   Vector vector1=new Vector();
   Vector vector2=new Vector();

   public Server() throws IOException
  {
    super(SERVER_PORT);
    try{
         while(true)
        {
          System.out.println("等待客户连接...");
          Socket socket=accept();
          new CreateServerThread(socket,vector1,vector2);
        }
       }catch(IOException e){System.out.println("客户连接错误");}
       finally
      {
         close();
      }
  }
  public static void main(String[] args)throws IOException
  {
       new Server();
  }
}
  class CreateServerThread extends Thread
 {
    Socket  socket;
    DataInputStream  in;
    DataOutputStream out;
    Vector   vector1;
    Vector   vector2;
    public boolean  bool=false;
    String     revStr=null;
    String     string=null;
    int        userID;
    String     str=null;
    Enumeration   enu;

    public CreateServerThread(Socket s,Vector vec1,Vector vec2)throws IOException
   {
     socket=s;
     vector1=vec1;
     vector2=vec2;
     out=new DataOutputStream(socket.getOutputStream());
     in=new DataInputStream(socket.getInputStream());
     start();
   }

   public void run()
  {
     StringTokenizer st;
     StringTokenizer stc;
     try{
           while(true)
          {
                revStr=in.readUTF();
                if(revStr.startsWith("新用户"))
               {
                   if(vector1.contains(revStr))
                   {
                       out.writeUTF("该用户已注册");
                   }
                  else
                  {
                      System.out.println("收到客户的登陆信息....."+revStr);
                      out.writeUTF("可以注册");
                      str=revStr;
                      vector1.add(revStr);
                      Enumeration enu=vector1.elements();
                      while(enu.hasMoreElements())
                      {
                         out.writeUTF((String)enu.nextElement());
                      }
                      bool=true;
                      Enumeration enuc=vector2.elements();
                      while(enu.hasMoreElements())
                     {
                         CreateServerThread th=(CreateServerThread)enuc.nextElement();
                         th.out.writeUTF(revStr);
                      }
                      stc=new StringTokenizer(revStr,":");
                      string=stc.nextToken();
                      string=stc.nextToken();
                      Enumeration enuc1=vector2.elements();
                      while(enuc1.hasMoreElements())
                      {
                             CreateServerThread th=(CreateServerThread)enuc1.nextElement();
                             th.out.writeUTF(string+"...上线了");
                      }
                      vector2.add(this);
                  }
               }
               else if(revStr.startsWith("下线了")||socket.isClosed())
               {
                   st=new StringTokenizer(revStr,":");
                   string=st.nextToken();
                   string=st.nextToken();
                   userID=vector1.indexOf(str);
                   vector1.remove(userID);
                   Enumeration enu=vector2.elements();
                   while(enu.hasMoreElements())
                  {
                       CreateServerThread th=(CreateServerThread)enu.nextElement();
                       if(th!=this&&th.isAlive())
                           th.out.writeUTF("下线了:"+str.substring(str.indexOf(":")+1));
                       th.out.writeUTF(str.substring(str.indexOf(":")+1)+"下线了");
                  }
                  vector2.remove(this);
                  break;
               }
               else
               {
                     enu=vector2.elements();
                     while(enu.hasMoreElements())
                     {
                             CreateServerThread th=(CreateServerThread)enu.nextElement();
                             th.out.writeUTF(revStr);
                     }
               }
          }
      }
      catch(IOException e)
      {
          try{
                userID=vector1.indexOf(str);
                vector1.remove(userID);
                Enumeration enun=vector2.elements();
                while(enun.hasMoreElements())
                {
                       CreateServerThread th=(CreateServerThread)enun.nextElement();
                       if(th!=this&&th.isAlive())
                       th.out.writeUTF("下线了:"+str.substring(str.indexOf(":")+1));
                       th.out.writeUTF(str.substring(str.indexOf(":")+1)+"...下线了");
                }
                vector2.remove(this);
                return;
             }catch(Exception ee){return;}
       }
  }
 }     

看到自己大三的程序还是倍感亲切的,我也米有运行,有错的地方,欢迎指正。毕竟快三年没写过java啦!

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值