程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> java中UDP簡單聊天程序實例代碼

java中UDP簡單聊天程序實例代碼

編輯:JAVA編程入門知識

學過計算機網絡通信的都知道,計算機之間傳送數據由兩種,即TCP通信和UDP通信。TCP是可靠的面向連接的通信協議,二UDP是不可靠的面向無連接的通信協議。

java中有基於TCP的網絡套接字通信,也有基於UDP的用戶數據報通信,UDP的信息傳輸速度快,但不可靠!

基於UDP通信的基本模式:

(1)將數據打包,稱為數據包(好比將信件裝入信封一樣),然後將數據包發往目的地。

(2)接受別人發來的數據包(好比接收信封一樣),然後查看數據包中的內容。

客戶機

代碼如下:

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;

/**
 * @author lenovo
 *
 */
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("客戶端");
  jta=new JTextArea();
  jtf=new JTextField(15);
  jb=new JButton("發送");
  jb.addActionListener(this);
  jp=new JPanel();
  jp.add(jtf);
  jp.add(jb);

  this.add(jta,"Center");
  this.add(jp,"South");
 // this.setTitle(ownerId+" 正在和 "+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>確定退出嗎?</html>","系統提示",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
    {  
     System.exit(0);
     ctsT.closeSocket();
    }
    else
    {
     return;
    }
   }
  }
  );
 }

 //寫一個方法,讓它顯示消息
 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;

/**
 * @author lenovo
 *
 */
public class ClientToServerThread extends Thread{

 private String serverIP = "127.0.0.1";
 private int serverPORT = 8888;
 private int receivePORT = 6666;
 //聲明發送信息的數據報套結字
    private DatagramSocket sendSocket = null;
    //聲明發送信息的數據包
    private DatagramPacket sendPacket = null;
    //聲明接受信息的數據報套結字
    private DatagramSocket receiveSocket = null;
    //聲明接受信息的數據報
    private DatagramPacket receivePacket = null;
    //收發數據的端口
    private int myPort = 0;
    //接收數據主機的IP地址
    private String friendIP = null;
    private int friendPort = 0;

    //緩沖數組的大小
    public static final int BUFFER_SIZE = 5120;

    private byte inBuf[] = null; //接收數據的緩沖數組
    private byte outBuf[] = null; //發送數據的緩沖數組

    JTextArea jta;

 // 構造函數
 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("收到數據"+message+"\n");
    } catch (Exception e) {
     e.printStackTrace();
     // TODO: handle exception
    }
   }
  }
 }
 /**
  * 該方法用來獲得服務器屬性文件中的IP、PORT
  */
 private void getPropertiesInfo(){
  Properties prop = new Properties();
  InputStream inStream = Thread.currentThread().getContextClassLoader()
    .getResourceAsStream("ServerInfo.properties");
  try{
   //獲得相應的鍵值對
   prop.load(inStream);
  }catch(IOException e){
   e.printStackTrace();
  }

  //根據相應的鍵獲得對應的值
  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();
    }
}

服務器:
代碼如下:

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;

/**
 * @author lenovo
 *
 */
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("服務器");
  jta=new JTextArea();
  jtf=new JTextField(15);
  jb=new JButton("發送");
  jb.addActionListener(this);
  jp=new JPanel();
  jp.add(jtf);
  jp.add(jb);

  this.add(jta,"Center");
  this.add(jp,"South");
 // this.setTitle(ownerId+" 正在和 "+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>確定退出嗎?</html>","系統提示",JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE)==0)
    {  
     System.exit(0);
     ctsT.closeSocket();
    }
    else
    {
     return;
    }
   }
  }
  );
 }

 //寫一個方法,讓它顯示消息
 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;

/**
 * @author lenovo
 *
 */
public class ClientToServerThread extends Thread{

 private String sendIP = "127.0.0.1"; 
 private int sendPORT = 6666;
 private int receivePORT = 8888;
 //聲明發送信息的數據報套結字
    private DatagramSocket sendSocket = null;
    //聲明發送信息的數據包
    private DatagramPacket sendPacket = null;
    //聲明接受信息的數據報套結字
    private DatagramSocket receiveSocket = null;
    //聲明接受信息的數據報
    private DatagramPacket receivePacket = null;
    //收發數據的端口
    private int myPort = 0;
    //接收數據主機的IP地址
    private String friendIP = null;
    private int friendPort = 0;

    //緩沖數組的大小
    public static final int BUFFER_SIZE = 5120;

    private byte inBuf[] = null; //接收數據的緩沖數組
    private byte outBuf[] = null; //發送數據的緩沖數組

    JTextArea jta;

 // 構造函數
 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("收到數據"+message+"\n");
    } catch (Exception e) {
     e.printStackTrace();
     // TODO: handle exception
    }
   }
  }
 }
 /**
  * 該方法用來獲得服務器屬性文件中的IP、PORT
  */
 private void getPropertiesInfo(){
  Properties prop = new Properties();
  InputStream inStream = Thread.currentThread().getContextClassLoader()
    .getResourceAsStream("ServerInfo.properties");
  try{
   //獲得相應的鍵值對
   prop.load(inStream);
  }catch(IOException e){
   e.printStackTrace();
  }

  //根據相應的鍵獲得對應的值

  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();
    }
}

運行截圖:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved