Example code of UDP simple chat program in Java

  • 2020-04-01 02:43:12
  • OfStack

Anyone who has studied computer network communication knows that there are two kinds of data transmission between computers, namely TCP communication and UDP communication. TCP is a reliable connection-oriented communication protocol, while UDP is an unreliable connectionless communication protocol.

There are network socket communication based on TCP in Java, there are also user datagram communication based on UDP, UDP information transmission speed is fast, but not reliable!

Basic mode of UDP based communication:

(1) the data is packaged, called a packet (like a letter in an envelope), and then sent to the destination.

(2) accept a packet from someone else (like an envelope) and then look at the contents of the packet.

The client


package com.client.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.tools.ClientToServerThread;

public class JChatFrm extends JFrame implements ActionListener{

 JTextArea jta;
 JTextField jtf;
 JButton jb;
 JPanel jp;
 String ownerId;
 String friendId;

 ClientToServerThread ctsT;
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  new JChatFrm();
 }

 public JChatFrm()
 {
  setTitle(" The client ");
  jta=new JTextArea();
  jtf=new JTextField(15);
  jb=new JButton(" send ");
  jb.addActionListener(this);
  jp=new JPanel();
  jp.add(jtf);
  jp.add(jb);

  this.add(jta,"Center");
  this.add(jp,"South");
 //  SetTitle (ownerId+" chatting with "+friend+");
  this.setIconImage((new ImageIcon("image/qq.gif").getImage()));
 // this.setSize(300, 200);
  this.setBounds(300, 200, 300, 200);
  this.setVisible(true);
  setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  ctsT = new ClientToServerThread(jta);
  ctsT.start();

  
  this.addWindowListener(new WindowAdapter()
  {
   public void windowClosing(WindowEvent e)
   {
    if(JOptionPane.showConfirmDialog(null, "<html><font size=3> Are you sure to quit? </html>"," The system prompt ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
    {  
     System.exit(0);
     ctsT.closeSocket();
    }
    else
    {
     return;
    }
   }
  }
  );
 }

 //Write a method that displays the message
 public void showMessage(String message)
 {
  String info= message;
  this.jta.append(info);
 }
 public void actionPerformed(ActionEvent arg0) {
  // TODO Auto-generated method stub
  if(arg0.getSource()==jb)
  {   
   byte buffer[] = jtf.getText().trim().getBytes();
   ctsT.sendData(buffer);
  }

 }
}


package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JTextArea;
import com.common.User;

public class ClientToServerThread extends Thread{
 private String serverIP = "127.0.0.1";
 private int serverPORT = 8888;
 private int receivePORT = 6666;
 //Declare the datagram nesting word that sends the message
    private DatagramSocket sendSocket = null;
    //Declare the packet that sends the message
    private DatagramPacket sendPacket = null;
    //A datagram that claims to accept information
    private DatagramSocket receiveSocket = null;
    //A datagram that claims to accept information
    private DatagramPacket receivePacket = null;
    //Port for sending and receiving data
    private int myPort = 0;
    //The IP address of the receiving data host
    private String friendIP = null;
    private int friendPort = 0;

    //Buffer the size of the array
    public static final int BUFFER_SIZE = 5120;
    private byte inBuf[] = null; //A buffered array of received data
    private byte outBuf[] = null; //A buffered array of sent data

    JTextArea jta;

 //The constructor
 public ClientToServerThread(JTextArea jta) {
  this.jta = jta;
  getPropertiesInfo();
 }
 public void run() {
  String receiveInfo = "";
  try{
   inBuf = new byte[BUFFER_SIZE];
   receivePacket = new DatagramPacket(inBuf,inBuf.length);
   receiveSocket = new DatagramSocket(receivePORT);
  }catch (Exception e) {
   e.printStackTrace();
   // TODO: handle exception
  }

  while (true) {
   if(receiveSocket == null){
    break;
   } else {
    try {
     receiveSocket.receive(receivePacket);
     String message = new String(receivePacket.getData(),0,receivePacket.getLength());
     jta.append(" Receive the data "+message+"n");
    } catch (Exception e) {
     e.printStackTrace();
     // TODO: handle exception
    }
   }
  }
 }
 
 private void getPropertiesInfo(){
  Properties prop = new Properties();
  InputStream inStream = Thread.currentThread().getContextClassLoader()
    .getResourceAsStream("ServerInfo.properties");
  try{
   //Get the corresponding key-value pair
   prop.load(inStream);
  }catch(IOException e){
   e.printStackTrace();
  }

  //Get the corresponding value according to the corresponding key
  serverIP = prop.getProperty("serverip");
  serverPORT = Integer.parseInt(prop.getProperty("serverudp.port"));
  receivePORT = Integer.parseInt(prop.getProperty("receiveudp.port"));

        
 }
 public void sendData(byte buffer[]){
  try{
   InetAddress address = InetAddress.getByName(serverIP);
  // outBuf = new byte[BUFFER_SIZE];
   sendPacket = new DatagramPacket(buffer,buffer.length,address,serverPORT);
   sendSocket = new DatagramSocket();
   sendSocket.send(sendPacket);
  }catch (Exception e) {
   e.printStackTrace();
   // TODO: handle exception
  }
 }
    public void closeSocket(){
     receiveSocket.close();
    }
}

Server:


package com.server.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.tools.ClientToServerThread;

public class JChatFrm extends JFrame implements ActionListener{

 JTextArea jta;
 JTextField jtf;
 JButton jb;
 JPanel jp;
 String ownerId;
 String friendId;

 ClientToServerThread ctsT;
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  new JChatFrm();
 }

 public JChatFrm()
 {
  setTitle(" The server ");
  jta=new JTextArea();
  jtf=new JTextField(15);
  jb=new JButton(" send ");
  jb.addActionListener(this);
  jp=new JPanel();
  jp.add(jtf);
  jp.add(jb);

  this.add(jta,"Center");
  this.add(jp,"South");
 //  SetTitle (ownerId+" chatting with "+friend+");
  this.setIconImage((new ImageIcon("image/qq.gif").getImage()));
 // this.setSize(300, 200);
  this.setBounds(300, 200, 300, 200);
  this.setVisible(true);
  setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  ctsT = new ClientToServerThread(jta);
  ctsT.start();

  
  this.addWindowListener(new WindowAdapter()
  {
   public void windowClosing(WindowEvent e)
   {
    if(JOptionPane.showConfirmDialog(null, "<html><font size=3> Are you sure to quit? </html>"," The system prompt ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
    {  
     System.exit(0);
     ctsT.closeSocket();
    }
    else
    {
     return;
    }
   }
  }
  );
 }

 //Write a method that displays the message
 public void showMessage(String message)
 {
  String info= message;
  this.jta.append(info);
 }
 public void actionPerformed(ActionEvent arg0) {
  // TODO Auto-generated method stub
  if(arg0.getSource()==jb)
  {      
   byte buffer[] = jtf.getText().trim().getBytes();
   ctsT.sendData(buffer);
  }

 }
}


package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Properties;
import javax.swing.JTextArea;
import com.common.User;

public class ClientToServerThread extends Thread{
 private String sendIP = "127.0.0.1"; 
 private int sendPORT = 6666;
 private int receivePORT = 8888;
 //Declare the datagram nesting word that sends the message
    private DatagramSocket sendSocket = null;
    //Declare the packet that sends the message
    private DatagramPacket sendPacket = null;
    //A datagram that claims to accept information
    private DatagramSocket receiveSocket = null;
    //A datagram that claims to accept information
    private DatagramPacket receivePacket = null;
    //Port for sending and receiving data
    private int myPort = 0;
    //The IP address of the receiving data host
    private String friendIP = null;
    private int friendPort = 0;
    //Buffer the size of the array
    public static final int BUFFER_SIZE = 5120;
    private byte inBuf[] = null; //A buffered array of received data
    private byte outBuf[] = null; //A buffered array of sent data

    JTextArea jta;

 //The constructor
 public ClientToServerThread(JTextArea jta) {
  this.jta = jta;
  getPropertiesInfo();
 }
 public void run() {
  String receiveInfo = "";
  try{
   inBuf = new byte[BUFFER_SIZE];
   receivePacket = new DatagramPacket(inBuf,inBuf.length);
   receiveSocket = new DatagramSocket(receivePORT);
  }catch (Exception e) {
   e.printStackTrace();
   // TODO: handle exception
  }

  while (true) {
   if(receiveSocket == null){
    break;
   } else {
    try {
     receiveSocket.receive(receivePacket);
     String message = new String(receivePacket.getData(),0,receivePacket.getLength());
     jta.append(" Receive the data "+message+"n");
    } catch (Exception e) {
     e.printStackTrace();
     // TODO: handle exception
    }
   }
  }
 }
 
 private void getPropertiesInfo(){
  Properties prop = new Properties();
  InputStream inStream = Thread.currentThread().getContextClassLoader()
    .getResourceAsStream("ServerInfo.properties");
  try{
   //Get the corresponding key-value pair
   prop.load(inStream);
  }catch(IOException e){
   e.printStackTrace();
  }

  //Get the corresponding value according to the corresponding key

  receivePORT = Integer.parseInt(prop.getProperty("serverudp.port"));

  

 }
 public void sendData(byte buffer[]){
  try{
   InetAddress address = InetAddress.getByName(sendIP);
  // outBuf = new byte[BUFFER_SIZE];
   sendPacket = new DatagramPacket(buffer,buffer.length,address,sendPORT);
   sendSocket = new DatagramSocket();
   sendSocket.send(sendPacket);
  }catch (Exception e) {
   e.printStackTrace();
   // TODO: handle exception
  }
 }
 public void closeSocket(){
     receiveSocket.close();
    }
}

Running screenshot:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131231160942038.jpg" >


Related articles: