java中UDP简单聊天程序

news/2024/5/18 13:17:08 标签: java, udp, 聊天, 网络, 通信

  学过计算机网络通信的都知道,计算机之间传送数据由两种,即TCP通信和UDP通信。TCP是可靠的面向连接的通信协议,二UDP是不可靠的面向无连接的通信协议。

  java中有基于TCP的网络套接字通信,也有基于UDP的用户数据报通信,UDP的信息传输速度快,但不可靠!

  基于UDP通信的基本模式:

 (1)将数据打包,称为数据包(好比将信件装入信封一样),然后将数据包发往目的地。

 (2)接受别人发来的数据包(好比接收信封一样),然后查看数据包中的内容。

客户机

java">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);
		}
			
	}
}

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

服务器:

java">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);
		}
			
	}
}


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

运行截图:





http://www.niftyadmin.cn/n/1294737.html

相关文章

RTXLinux编程

2019独角兽企业重金招聘Python工程师标准>>> RTlinux主要的api函数 实时应用程式分为两部分,内核部分和应用部分,应用部分需要和内核部分通过FIFO进行数据交换和控制,除此之外和一般应用程式没有太多区分,内核部分比较复杂,程式以模块方式挂入内核,这部分程式的编写…

python导入代码步骤_python导入pandas具体步骤方法

Pandas最初被作为金融数据分析工具而开发出来&#xff0c;因此&#xff0c;pandas为时间序列分析提供了很好的支持。 Pandas的名称来自于面板数据&#xff08;panel data&#xff09;和python数据分析&#xff08;data analysis&#xff09;。panel data是经济学中关于多维数据…

VC版学生成绩管理系统

VC版学生成绩管理系统 一&#xff0e; 功能需求&#xff1a; 1. 能进行对数据库的连接&#xff08;后台&#xff09;&#xff1a; 这是查询管理信息的基础。 2. 能进行增、删、改、查等基本功能&#xff1a; 这是学生成绩管理系统最基本的功能&#xff0c;可以在这个…

rust编程之道_【Rust日报】 20190414

laminar - 面向多玩家游戏的半可靠 UDP 协议这是 amethyst 项目下的底层网络库&#xff0c;可以独立使用。提供了可靠传输与不可靠传输的选择。发包use laminar::{Socket, Packet};// create the socketlet (mut socket, packet_sender, _) Socket::bind("127.0.0.1:1234…

label 字间距 行间距设置

label 字间距 行间距设置 群里讨论看到 &#xff0c;先记下来&#xff0c;会用到的。在drowInrect里//设置字间距if(self.characterSpacing){long number self.characterSpacing;CFNumberRef num CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);[strin…

python中ttk和tkinter_Tkinter和ttk在python 2.7中

我正在关注在Python中创建GUI的Sentdex教程found here&#xff0c;specifically this part . 但是教程是在python 3中&#xff0c;我使用的是2.7 . 导入 Tkinter 很好&#xff0c;但是当我导入 ttk 然后将其继承到类中时会出现问题 . 在python 2.7中 ttk 是一个单独的模块&…

最长上升子序列 LIS(Longest Increasing Subsequence)

引出&#xff1a; 问题描述:给出一个序列a1,a2,a3,a4,a5,a6,a7….an,求它的一个子序列&#xff08;设为s1,s2,…sn&#xff09;&#xff0c;使得这个子序列满足这样的性质&#xff0c;s1<s2<s3<…<sn并且这个子序列的长度最长。输出这个最长的长度。&#xff08;为…

python标注_python怎么标注

广告关闭 腾讯云11.11云上盛惠 &#xff0c;精选热门产品助力上云&#xff0c;云服务器首年88元起&#xff0c;买的越多返的越多&#xff0c;最高返5000元&#xff01;个时候&#xff0c;如果你使用的是python 3&#xff0c;那么你可以使用类型标注来告诉pycharm&#xff0c;这…