Home  >  Article  >  Java  >  How to implement a simple chat program using network communication technology in Java

How to implement a simple chat program using network communication technology in Java

王林
王林forward
2023-04-23 10:19:061115browse

First is the server code:

package ChatTwoPackage;
 
import java.io.*;
import java.net.*;
 
public class ChatTwoServer {
 
 public ChatTwoServer(int port,String name) throws IOException
 {
 ServerSocket server=new ServerSocket(port);//创建seversocket对象,提供tcp连接服务。指定端口port,等待tcp连接。
 System.out.print("正在等待连接,请勿操作!");
 Socket client=server.accept();//创建socket对象,它等待接收客户端的连接。
 new ChatTwoClient(name,client);//实现图形界面。
 server.close();
 }
 
 public static void main(String[] args) throws IOException {
 new ChatTwoServer(2001,"SQ");
 
 }
 
}

Then is the client code:

package ChatTwoPackage;
 
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
 
public class ChatTwoClient extends JFrame implements ActionListener {
 private String name;
 private JTextArea text_re;
 private JTextField text_se;
 private PrintWriter cout;
 private JButton buttons[];
 public ChatTwoClient(String name,Socket socket) throws IOException
 {
 super("我:"+name+InetAddress.getLocalHost().getHostAddress()+":"+socket.getLocalPort());
 this.setBounds(320, 240, 400, 240);
 this.text_re=new JTextArea();
 this.text_re.setEditable(false);
 this.getContentPane().add(new JScrollPane(this.text_re));
 
 JToolBar toolBar=new JToolBar();
 this.getContentPane().add(toolBar,"South");
 toolBar.add(this.text_se=new JTextField(30));
 buttons=new JButton[2];
 buttons[0]=new JButton("发送");
 buttons[1]=new JButton("下线");
 toolBar.add(buttons[0]);
 toolBar.add(buttons[1]);
 buttons[0].addActionListener(this);
 buttons[1].addActionListener(this);//给按钮添加事件监听,委托当前对象处理
 this.setVisible(true);
 this.name=name;
 this.cout=new PrintWriter(socket.getOutputStream(),true);//获得socket输出流
 this.cout.println(name);
 BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream())); //将socket的字节输入流转换为字符流,默认GBK字符集,再创建缓冲字符输入流
        String line="连接"+br.readLine()+"成功";
        while(line!=null&&!line.endsWith("bye"))
 {
  text_re.append(line+"\r\n");
  line=br.readLine();
 }//读取对方发送的内容并显示,直到内容为为空或对方下线
 br.close();
 this.cout.close();
 socket.close();
 buttons[0].setEnabled(false);
 buttons[1].setEnabled(false);
 }
 public ChatTwoClient(String name,String host,int port) throws IOException
 {
 this(name,new Socket(host,port));//调用另一个构造方法
 }
 public void actionPerformed(ActionEvent ev)
 {
 if(ev.getActionCommand().equals("发送"))
 {
  this.cout.println(name+":"+text_se.getText());
  text_re.append("我:"+text_se.getText()+"\n");
  text_se.setText("");
 }//按下发送按钮后,将内容发出,并更新自己聊天框的内容
 if(ev.getActionCommand().equals("下线"))
 {
  text_re.append("你已下线\n");
  this.cout.println(name+"离线\n"+"bye\n");
  buttons[0].setEnabled(false);
  buttons[1].setEnabled(false);
 }//下线按钮按下后,发送bye作为下线标记
 }
 
 
 public static void main(String[] args) throws IOException {
 new ChatTwoClient("mxl","127.0.0.1",2001); //ip地址和端口
 
 }
 
}

Running effect:

How to implement a simple chat program using network communication technology in Java

Description:

1. Two computers and one as the server. The computer as the server needs two codes. First run the server code and wait for the client machine to connect. After the client runs the client code, it will prompt that the connection is successful. You can send the message.

2. Before running the code, you need to change the IP address to the current IP address of your computer (a computer that accesses the Internet through Modem, ISDN, ADSL, cable broadband, community broadband, etc., the IP address assigned each time you access the Internet are all different, this is called a dynamic IP address). If you want to use one computer to act as client and server, write the IP address as: 127.0.0.1 (127.0.0.1 is the loopback address, referring to the local machine, generally used for testing). Just run the server code first and then the client code.

The above is the detailed content of How to implement a simple chat program using network communication technology in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete