java编写的socket聊天程序(登录)

来源:互联网 发布:黄金分析软件哪个好 编辑:程序博客网 时间:2024/03/28 21:18

package MyChatRoom;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MyChatRoom
{
 public static void main(String Args [])
 {
  logFrame log=newlogFrame();
 }
}
//聊天模块
class MyFrame extends JFrame implements ActionListener
{
 public MyFrame(int a,String ip)
 {
  //获取传来的参数
  ipA=ip;
  selectNum=a;
  //基本设置
  setTitle("Sun聊天小工具");
  setSize(WIDTH,HEIGHT);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  //创建3个面板,一个放文本框,一个放按钮,一个放图片
  JPanel textpanel = newJPanel();
  JPanel buttonPanel=newJPanel();
  JPanel picPanel=newJPanel();
  Container contentPane =getContentPane();
  
  GridBagConstraints cc=newGridBagConstraints();
  GridBagLayout ca=newGridBagLayout();
  contentPane.setLayout(ca);
  cc.fill=GridBagConstraints.BOTH;
  //初始化一个容器
  cc.gridwidth=1;
  cc.gridheight=2;
  contentPane.add(picPanel);
  ca.setConstraints(picPanel,cc);
  cc.weighty=0.0;
  cc.gridwidth=GridBagConstraints.REMAINDER;
  cc.gridheight=1;
  cc.weighty=1.0;
  contentPane.add(textpanel);
  ca.setConstraints(textpanel,cc);
  contentPane.add(buttonPanel);
  ca.setConstraints(buttonPanel,cc);
  
  
  
  //网格式布局
  GridBagConstraints c=newGridBagConstraints();
  GridBagLayout gridbag=newGridBagLayout();
  textpanel.setLayout(gridbag);
  c.fill=GridBagConstraints.BOTH;
 
 
  
  //初始化组件
  //发送按钮
  btSet=new JButton("发送");
  buttonPanel.add(btSet);
  btSet.addActionListener(this);
  
  //取消按钮
  btCancel=newJButton("取消");
  buttonPanel.add(btCancel);
  btCancel.addActionListener(this);
  
  //清空按钮
  btClear=newJButton("清屏");
  buttonPanel.add(btClear);
  btClear.addActionListener(this);
  
  //显示消息框
  c.weightx=1.0;
  c.weighty=1.0;
  c.gridwidth=GridBagConstraints.REMAINDER;
  getBox=newJTextArea(15,30);
  getBox.setEditable(false);
  myScro=newJScrollPane(getBox);
  textpanel.add(myScro);
  gridbag.setConstraints(myScro,c);
 
  //设置文本框显示数据往下翻页
  getBox.setCaretPosition(getBox.getText().length());
  
  //标签项
  c.weightx=1.0;
  c.gridwidth=GridBagConstraints.RELATIVE;;
  label1=new JLabel("输入");
  label4=newJLabel("聊天内容");
  c.gridwidth=GridBagConstraints.REMAINDER;
  gridbag.setConstraints(label4,c);
  textpanel.add(label1);
  textpanel.add(label4);
 
  //发送消息框
  setBox=newJTextArea(7,30);
  myScro2=newJScrollPane(setBox);
  textpanel.add(myScro2);
  gridbag.setConstraints(myScro2,c); 
  
  //菜单项
  //主菜单
  JMenuBar menuBar = newJMenuBar();
  setJMenuBar(menuBar);
  gyMenu =newJMenu("关于(G)");
  bzMenu =newJMenu("帮助(H)");
  editMenu =newJMenu("编辑(E)");
  szMenu =newJMenu("设置(S)");
  menuBar.add(editMenu);
  menuBar.add(gyMenu);
  menuBar.add(bzMenu);
  menuBar.add(szMenu);
  
  
  //子菜单
  aa =new JMenuItem("版权");
  zzxx =newJMenuItem("作者信息");
  gyMenu.add(aa);
  gyMenu.add(zzxx);
  aa.addActionListener(this);
  zzxx.addActionListener(this);
  cop=new JMenuItem("复制");
  cut =new JMenuItem("剪切");
  pas =new JMenuItem("粘贴");
  editMenu.add(cop);
  editMenu.add(cut);
  editMenu.add(pas);
  cop.addActionListener(this);
  cut.addActionListener(this);
  pas.addActionListener(this);
  syzn=newJMenuItem("使用指南");
  bzMenu.add(syzn);
  syzn.addActionListener(this);
  pifu=newJMenuItem("字体颜色");
  beijing=newJMenuItem("背景色");
  touxiang=newJMenuItem("更换头像");
  szMenu.add(pifu);
  szMenu.add(beijing);
  szMenu.add(touxiang);
  pifu.addActionListener(this);
  beijing.addActionListener(this);
  touxiang.addActionListener(this);
 
  //匿名内部类实现监听
  setBox.addKeyListener(newKeyAdapter()
   {
    publicvoid keyPressed(KeyEvent e)
     {
      //当按回车时发送所输入的信息
      if(e.getKeyCode()==KeyEvent.VK_ENTER)
      {
       sendString=setBox.getText();
         out.println(sendString);
         getBox.setCaretPosition(getBox.getText().length());
         getBox.append("I Said:"+sendString+"\r\n");
         setBox.setText("");
         setBox.setCaretPosition(0);    
      }
     }
   });
  
  imgLabel1=new JLabel(newImageIcon("./MyChatRoom/bb.jpg"));
       picPanel.add(imgLabel1);
       imgLabel2=new JLabel(new ImageIcon("./MyChatRoom/aa.jpg"));
       picPanel.add(imgLabel2);
       picPanel.setLayout(new GridLayout(2,1));
       
       //显示窗口 
       setVisible(true);

  //选择作为客户端还是服务器端
  switch(selectNum)
  {
   case 0:
    serverRole();
    break;
   case 1:
    clientRole();
    break;
  }
  
  //启动线程处理输入流
       thread=new MyThread(connectSocket,getBox);
       thread.setPriority(Thread.MIN_PRIORITY);
       thread.start();
       
       //包装输出流
       try
           {
               out=new PrintWriter(new BufferedWriter(newOutputStreamWriter(connectSocket.getOutputStream())),true);
           }
       catch(IOException e)
           {
            e.printStackTrace();
           }
           
 }
 
 final int WIDTH=550;
 final int HEIGHT=600;
 JLabel label1,label4,imgLabel1,imgLabel2;
 JButton btSet,btCancel,btClear;
 JTextArea setBox,getBox;
 JMenu gyMenu,bzMenu,editMenu,szMenu;
 JMenuItemaa,cop,cut,pas,zzxx,syzn,pifu,beijing,touxiang;
 JScrollPane myScro,myScro2;
 String sendString;
 MyThread thread=null;
    ServerSocketserverSocket=null;;
    SocketconnectSocket=null;;
    StringipA;
    PrintWriterout=null;;
    intselectNum;
    StringimgPath;

   //作为服务器端的处理
    public voidserverRole()
    {
    try
     {
            serverSocket=new ServerSocket(5500);
               getBox.append("正在等待对话请求\n");
               connectSocket=serverSocket.accept();
               getBox.setText("连接来自"+connectSocket.getInetAddress().toString()+"\n");
     }
    catch(Exception e)
    {
          getBox.append("对不起,由于某些原因,不能创建服务器\n");
               btSet.setEnabled(false);
    }
    }
    //作为客户端的处理
    public voidclientRole()
    {
    try
     {
             connectSocket=new Socket(ipA,5500);
             getBox.setText("成功连接至"+ipA+"\n");
     }
    catch(Exception e)
    {
         getBox.append("对不起,无法连接!\r\n请重新登录并输入正确的IP地址");
           btSet.setEnabled(false);
    }
    }
    //按钮监听
 public void actionPerformed(ActionEvent e)
 
  Object o=e.getSource();
 
   //发送按钮处理
  if(o==btSet)
  {
   sendString=setBox.getText();
   out.println(sendString);
   getBox.setCaretPosition(getBox.getText().length());
   getBox.append("ISaid:"+sendString+"\r\n");
   setBox.setText(""); 
   setBox.setCaretPosition(setBox.getText().length());    
  }
  //取消按钮处理
  if(o==btCancel)
  {
   setBox.setText("");
  }
  //清空按钮处理
  if(o==btClear)
  {
   getBox.setText("");
  }
  //复制处理
  if(o==cop)
  {
   getBox.copy();
  }
  //剪切处理
  if(o==cut)
  {
   getBox.cut();
  }
  //粘贴处理
  if(o==pas)
  {
   setBox.paste();
  }
  if(o==zzxx)
  {
   JOptionPane.showMessageDialog(this,"作者:沈光辉,学号:20095392");
  }
  if(o==aa)
  {
   JOptionPane.showMessageDialog(this,"版权所有,盗版必究!");
  }
  if(o==syzn)
  {
   JOptionPane.showMessageDialog(this,"请等待消息框显示连接信息后再进行通信");
  }
  //打开调色板设置背景色
  if(o==pifu)
  {
    Colorcolor=JColorChooser.showDialog(this, "调色板",this.getBackground());
            if(color!=null)
            getBox.setForeground(color);
            setBox.setForeground(color);
   
  }
  if(o==beijing)
  {
    Colorcolor=JColorChooser.showDialog(this, "调色板",this.getBackground());
            if(color!=null)
            getBox.setBackground(color);
            setBox.setBackground(color);
   
  }
  //更改头像
  if(o==touxiang)
  {
   JFileChooserchooser=newJFileChooser("F:/文件/本学期相关课件/Java高级应用代码/MyChatRoomProgram/MyChatRoom");
   //设置过滤条件
   FileNameExtensionFilterfilter=new FileNameExtensionFilter("图片文件——jpg","jpg");
   //获取当前文件目录
   Filefile=chooser.getCurrentDirectory();
   //设置当前文件目录
   chooser.setCurrentDirectory(file);
   //设置过滤器
   chooser.setFileFilter(filter);
   inti=chooser.showDialog(this,"选择");
   if(i==JFileChooser.APPROVE_OPTION)
    {
    imgPath=chooser.getSelectedFile().getAbsolutePath();
    //创建ImageIcon对象
    ImageIcon img=new ImageIcon(imgPath);
    //创建Image对象,ImageIcon的getImage()方法返回该类型对象
    Image sourceImg=img.getImage();
    //该方法用来缩放图像、
    ImagescaleImg=sourceImg.getScaledInstance(200,250,Image.SCALE_DEFAULT);
    //setIcon(Icon icon)
    imgLabel1.setIcon(newImageIcon(scaleImg)); 
   
      
   

  }
 }
 
}
//线程类1,用来处理输入流数据显示
class MyThread extends Thread
{
 BufferedReader in=null;
 String inStr=null;
 JTextArea getBox;
 
 //用构造方法传入socket和文本域以作相应的处理
 public MyThread(Socket soc,JTextArea a)
 {
  getBox=a;
  try
  {
   in =newBufferedReader(new InputStreamReader(soc.getInputStream()));
  }
  catch(IOException e)
  {
   e.printStackTrace();
  }
  
 }
 //run方法
 public void run()
 {
  try
  {
   while(true)
   {
    inStr=in.readLine();
    getBox.setCaretPosition(getBox.getText().length());
    getBox.append("Hesaid:"+inStr+"\r\n");
    Thread.sleep(500); 
   }
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}
//登录验证模块
class logFrame extends JFrame implements ActionListener
{
 //构造方法
 public logFrame()
 {
  
  //主面板
  setTitle("用户登录");
  setSize(400,270);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Containercotn=getContentPane();
    
    //添加面板
  JPanel panel1=newJPanel();
  JPanel panel2=newJPanel();
  JPanel panel3=newJPanel();
  JPanel panel4=newJPanel();
  JPanel panel5=newJPanel();
  JPanel panel6=newJPanel();
  cotn.add(panel6);
  cotn.add(panel1);
  cotn.add(panel2);
  cotn.add(panel4);
  cotn.add(panel3);
  cotn.add(panel5);
  
  //网格式布局
  cotn.setLayout(newGridLayout(6,1));
  
  //添加组件
  user=new JLabel("用 户 名");
  pass=newJLabel("密     码");
  ipLabel=new JLabel("I P地址");
  userName=newJTextField(20);
  passWord=newJPasswordField(20);
  ipAdd=newJTextField("localhost",20);
  ipAdd.setEditable(false);
  panel1.add(user);
  panel1.add(userName);
  panel2.add(pass);
  panel2.add(passWord);
  panel3.add(ipLabel);
  panel3.add(ipAdd);
  
  headLabel=newJLabel("用户登录");
  panel6.add(headLabel);
  
  //选择作为服务器端还是客户端
  serverR=newJRadioButton("服务器端",true);
  clientR=newJRadioButton("客户端",false);
  myGroup=newButtonGroup();
  myGroup.add(serverR);
  myGroup.add(clientR);
  panel4.add(serverR);
  panel4.add(clientR);
  serverR.addActionListener(this);
  clientR.addActionListener(this);
  serverR.addKeyListener(newlogListener());
  clientR.addKeyListener(newlogListener());
  
  //登录按钮
  btOk=new JButton("登录");
  btCanc=new JButton("退出");
  panel5.add(btOk);
  panel5.add(btCanc);
  btOk.addActionListener(this);
  btCanc.addActionListener(this);
  btOk.addKeyListener(newlogListener());
  btCanc.addKeyListener(newlogListener());
  
  //菜单项
  JMenuBar mainMenu=newJMenuBar();
  setJMenuBar(mainMenu);
  bz=new JMenu("帮助");
  gy=new JMenu("关于");
  mainMenu.add(gy);
  mainMenu.add(bz);
  bb=new JMenuItem("版本");
  gy.add(bb);
  bb.addActionListener(this);
  gySun=newJMenuItem("关于Sun");
  gy.add(gySun);
  gySun.addActionListener(this);
    syxz=new JMenuItem("使用指南");
  bz.add(syxz);
  syxz.addActionListener(this);
  
  //为组件添加键盘事件监听
  userName.addKeyListener(newlogListener());
  passWord.addKeyListener(newlogListener());
  ipAdd.addKeyListener(newlogListener());
  
  //显示窗口。最后才显示,防止面板有些元素不能正常显示。
  setVisible(true);
  
 }
 JMenu bz,gy;
 JMenuItem bb,gySun,syxz;
 JTextField userName,ipAdd;
 JPasswordField passWord;
 JLabel user,pass,ipLabel,headLabel;
 ButtonGroup myGroup;
 JRadioButton serverR,clientR;
 JButton btOk,btCanc;
 //num选择的角色
 public int num;
 String ipAddress;
 //内部类实现监听
 class logListener extends KeyAdapter
 {
  public void keyPressed(KeyEvente)
  
   if(e.getKeyCode()==KeyEvent.VK_ENTER)
   {
    //键盘确定选择是客户端
    if(e.getSource()==clientR)
    {
     clientR.setSelected(true);
     ipAdd.setEditable(true);
     ipAdd.setCaretPosition(ipAdd.getText().length());
     num=1;
    }
    //键盘确定选择是服务器端
      else if(e.getSource()==serverR)
      {
       serverR.setSelected(true);
       ipAdd.setEditable(false);
       num=0;
       
      }
      //键盘确定选择是退出按钮
      else if(e.getSource()==btCanc)
      {
       System.exit(0);
      }
      //键盘确定选择的是其他组件,则默认进行登录验证
      else
    logTest();
   }
    
  }
 }
 //登录验证方法
 public void logTest()
 {
  Strings1=userName.getText().trim();
    String s2=passWord.getText().trim();
    String s3=ipAdd.getText().trim();
    if(s1.equals("20095392"))
     {
      headLabel.setText("正在连接...");
    ipAddress=ipAdd.getText().trim();
    //创建线程,启动聊天窗口
    logThreadca=new logThread(num,ipAddress);
    //启动
      ca.start();
      //释放登录窗口资源
      logFrame.this.dispose();
     }
    else
     {
      JOptionPane.showMessageDialog(this,"用户名不存在或密码错误!");
      passWord.setText("");
     }
    
 }
 //按钮事件实现
 public void actionPerformed(ActionEvent e)
 {
  Object o=e.getSource();
  //选择的是服务器端
  if(o==serverR)
  {
   num=0;
   ipAdd.setEditable(false);
  }
  //选择的是客户端
  if(o==clientR)
  {
   num=1;
   ipAdd.setEditable(true);
   ipAdd.setCaretPosition(ipAdd.getText().length());
   ipAdd.requestFocus(true);
  }
  //登录验证
  if(o==btOk)
  {
   logTest();
   
  }
  //取消登录,退出系统
  if(o==btCanc)
  {
   System.exit(0);
  }
  if(o==syxz)
  {
   JOptionPane.showMessageDialog(this,"请先选择本客户端的角色(服务器端或客户端)\r\n若选择客户端请输入所要连接的服务器端IP地址");
  }
  if(o==bb)
  {
   JOptionPane.showMessageDialog(this,"Version-1.0");
  }
  if(o==gySun)
  {
   JOptionPane.showMessageDialog(this,"作者-沈光辉学号-20095392");
  }
 }
}
//线程类2,用来启动聊天窗口模块
class logThread extends Thread
{
 int num=0;
 String ipA;
 //run方法
 public logThread(int n,String ip)
 {
  num=n;
  ipA=ip;
 }
 public void run()
 {
 
  try
   {
     {
      MyFramea=new MyFrame(num,ipA);
      Thread.sleep(1000); 
     }
        }
        catch(Exception e)
        {
         e.printStackTrace();
        }
 }
}

0 0
原创粉丝点击