java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > UDP简单聊天程序

java中UDP简单聊天程序实例代码

作者:

这篇文章主要介绍了java中UDP简单聊天程序实例代码,有需要的朋友可以参考一下

学过计算机网络通信的都知道,计算机之间传送数据由两种,即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();
    }
}

运行截图:

您可能感兴趣的文章:
阅读全文