⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatclient.java

📁 提供给大家共享啊,可以参考一下,如果说有更好的可以给我发一下了
💻 JAVA
字号:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class ChatClient implements Runnable{
  /*以下用于定义UI变量*/
  JFrame frame = new JFrame();
  JPanel contentPane;
  BorderLayout borderLayout = new BorderLayout();  
  GridLayout gridLayout = new GridLayout(3,1);  
  Panel panel0 = new Panel();        //用于放置panel1,panel2,panel3
  Panel panel1 = new Panel();        //用于放置输入服务器地址
  Panel panel2 = new Panel();        //用于放置输入姓名和连接两个按钮
  Panel panel3 = new Panel();        //用于放置发送信息区域
  Panel panel4 = new Panel();        //用于放置聊天信息显示和聊天人员列表
  Panel panel5 = new Panel(); 
  Label label1 = new Label();
  TextField add_txt = new TextField(36);
  Label label2 = new Label();
  TextField name_txt = new TextField(20);
  Button button1 = new Button();
  Button button2 = new Button();
  Label label3 = new Label();
  TextField msg_txt = new TextField(30);
  Button button3 = new Button();
  TextArea chat_txt = new TextArea(15,30);
  java.awt.List list1 = new java.awt.List(16);
  
  /*以下定义数据流和网络变量*/
  Socket soc=null;                   //定义连接套接字
  DataInputStream dis=null;          //定义用来实现客户端接受服务器数据的输入流
  DataOutputStream dos=null;          //定义用来实现从客户端发送数据到服务器的输出流
  Thread client=null;             //定义一个客户端线程

  public ChatClient()          //初始化图形界面
  {
    frame.setTitle("聊天客户端");
    contentPane = (JPanel) frame.getContentPane();
    contentPane.setLayout(borderLayout);
    panel0.setLayout(gridLayout);
    label1.setText("服务器地址:");
    add_txt.setText("localhost");
    panel1.add(label1);
    panel1.add(add_txt);
    panel1.setBackground(Color.orange);
    panel0.add(panel1);
    label2.setText("姓            名:");    
    button1.setLabel("连接");
    button2.setLabel("断开连接");
    panel2.add(label2);
    panel2.add(name_txt);
    panel2.add(button1);
    panel2.add(button2);
    panel2.setBackground(Color.orange);
    panel0.add(panel2);
    label3.setText("聊 天 信 息:");
    msg_txt.setText("请输入聊天信息");
    button3.setLabel("发送");
    panel3.add(label3);
    panel3.add(msg_txt);
    panel3.add(button3);
    panel3.setBackground(Color.orange);
    panel0.add(panel3);
    panel0.setBackground(Color.orange);
    contentPane.add(panel0, BorderLayout.NORTH);
    chat_txt.setEditable(false);
    panel4.add(chat_txt);
    panel4.add(list1);
    panel4.setBackground(Color.orange);
    contentPane.add(panel4, BorderLayout.SOUTH);
    panel5.setBackground(Color.orange);
    contentPane.add(panel5, BorderLayout.CENTER);
    ButtonAction buttonaction = new ButtonAction();
    button1.addActionListener(buttonaction);
    button2.addActionListener(buttonaction);
    button3.addActionListener(buttonaction);
    frame.setSize(450,380); 
    frame.setResizable(false); 
    frame.addWindowListener(new WindowAdapter()
         {  public void windowClosing(WindowEvent e)
            {  disconnect();
               System.exit(0);}
         });
    frame.show();
  }

  public static void main(String[] args) 
  {
     ChatClient cc=new ChatClient();
  }

  public void connect()                                         //客户端点击连接要运行的方法
  {
     if(soc==null)
		{
	     try
			{
		     soc=new Socket(add_txt.getText(),1234);    //使用端口1234实例化一个本地套接字
			System.out.println(soc);                             //在控制台打印实例化的结果
			dis=new DataInputStream(soc.getInputStream());           //将dis指向soc的输入流
                        dos=new DataOutputStream(soc.getOutputStream());           //将dos指向soc的输出流
			String infos=new String("INFO: ");        //定义一个字符串存储发送信息,其中INFO为关键字让服务器识别为连接信息
								//并将name和ip用":"分开,在服务器端将用一个StringTokenizer类来读取数据
			String userinfo=name_txt.getText()+":"+InetAddress.getLocalHost().toString();
			dos.writeUTF(infos+userinfo);
			client=new Thread(this);    //将客户端线程实例化  
			client.start();                                    //启动线程
			}
		catch(IOException e)
			{
		     System.out.println("Error:"+e);
			disconnect();
				 }
			 }   //end of if
  }

  public void disconnect()                                         //客户端点击断开连接要运行的方法
  {
     if(soc!=null)
		{
	     try
			{
		     client.suspend();
			dos.writeUTF("QUIT");                                    //用输出流发送QUIT信息通知服务器断开此次通信
			soc.close();                                           //关闭套接字
		        soc=null;
                        }
		 catch(IOException e)
			{
		     System.out.println("Error:"+e);
		 }
	 }// end of if
  }

  public void send()                                         //客户端点击发送要运行的方法
  {
     if(soc!=null)
		{
	     String msgs=new String("MSG: ");        //定义并实例化一个字符串存储发送的聊天信息,其中MSG为关键词
		try
			{
		     dos.writeUTF(msgs+msg_txt.getText());          //用输出流发送聊天信息
			}
		catch(IOException e)
                        {
                     System.out.println("Error:"+e);
                } 
	}
  }
 
  public void run()                               //线程运行方法
  {
      String msg=null;
	  while(true)
		{
	     try{msg=dis.readUTF();}                 //读取从服务器传来的信息
		 catch(IOException e)
			{
		     System.out.println("Error:"+e);
		     disconnect();
		 }
		 if (msg==null)                           //如果从服务器传来的信息为空则断开此次连接
		 {
		   client=null;              
		   soc=null;
		   list1.clear();
		 }
		 StringTokenizer st=new StringTokenizer(msg,":");   //用StringTokenizer类来实现读取分段字符
		 String keyword=st.nextToken();                     //读取信息头即关键字用来识别是何种信息

		 if(keyword.equals("PEOPLE"))                      //如果是PEOPLE则是服务器发来的客户连接信息
		                                                   //主要用来刷新客户端的用户列表
			{
		         list1.clear();
			 while(st.hasMoreTokens())                     //遍历st取得目前所连接的客户
				{
			         String str=st.nextToken();
				 list1.addItem(str);
			 }
		 }
		 else if(keyword.equals("MSG"))                   //如果关键字是MSG则是服务器传来的聊天信息
		                                                  //主要用来刷新客户端聊天信息区将每个客户的聊天内容显示出来
			{
		     String usr=st.nextToken();
			 chat_txt.appendText(usr);
			 chat_txt.appendText(st.nextToken("\0"));
			 chat_txt.appendText("\n\n");
		 }
		 else if(keyword.equals("QUIT"))                //如果关键字是QUIT则是服务器关闭的信息
		                                                //用来切断此次连接
			{
		     System.out.println("Quit");
		     try
		     {
                      client.stop();
		      client=null;
		      soc.close();
		      soc=null;
             }catch(IOException e)
             {
             	System.out.println("Error:"+e);
             	}
			 list1.clear(); 
		 }
	  }
  }     //end of run method

  class ButtonAction implements ActionListener
  {
    public void actionPerformed(ActionEvent event)       //事件触发代码
    {  
      Object source=event.getSource();
	   if(source==button1)                //如果点击连接按钮则运行connect()
	         {
		 connect();    
		 }//end of if
	   else if(source==button2)                             //如果点击断开连接按钮则运行disconnect()
			{
	         disconnect();
	   }
	   else if(source==button3)                                  //如果点击发送按钮则运行send()
			{
	         send();
	   }
     }
  }   //end of ButtonAction class
}     //end of ChatClient class

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -