Java基于UDP通信聊天室代码

UDP就是将目的地和数据封装在一个包中,然后发送给相应的目的地,包的大小最大为64K,安全性低,效率高

在创建之前我们余姚知道一些类和方法的用法

比如:InetAdress类

//得到名为zhang的主机对象
InetAddress iAddress=InetAddress.getByName("zhang");
//得到该对象的ip地址
String hostIp=iAddress.getHostAddress();
//获得本地主机对象
InetAddress iAddress2=InetAddress.getLocalHost();
//得到该对象的ip地址
String hostip1=iAddress2.getHostAddress();
//得到该主机的名字
String hostName=iAddress2.getHostName();
//得到名为zhang的计算机的所有ipv4和ipv6链接
InetAddress[] iAddress3=InetAddress.getAllByName("zhang");
for (int i = 0; i < iAddress3.length; i++) {
	System.out.println(iAddress3[i].getHostAddress());
}
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp=new DatagramPacket();

UDP发包

package net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UDPClient implements Runnable {

	//目的端口
	private int port;

	//目的ip
	private String ip;

	//初始化ip和端口
	public UDPClient(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}
	@Override
	public void run() {
		UDPClient uClient=new UDPClient(ip, port);
		uClient.UDPClient();
	}
	public void UDPClient() {
		//定义socket对象,实现通信
		DatagramSocket dSocket = null;
		//高效读
		BufferedReader bReader = null;
		try {
			//得到目的ip的主机对象
			InetAddress iAddress1=InetAddress.getByName(ip);
			System.out.println("已接入"+iAddress1.getHostName());
			while (true) {
				//从控制台读取
				bReader = new BufferedReader(new InputStreamReader(System.in));
				//读取一行数据
				String string = bReader.readLine();
				//定义socket对象,实现通信
				dSocket = new DatagramSocket();
				//把读到的字符串转码为utf-8字符数组
				byte[] by = string.getBytes("utf-8");//两个客户端务必编码一致,不然会乱码
				InetAddress iAddress = InetAddress.getByName(ip);
				//创建数据包
				DatagramPacket dPacket = new DatagramPacket(by, by.length, iAddress, port);
				//发送数据包
				dSocket.send(dPacket);
				System.out.println("你对" + iAddress.getHostName() + "说:" + string);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (dSocket != null) {
				dSocket.close();
			}
		}
	}

}

UDP收包

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer implements Runnable {

	//接受端口
	private int port;

	//构造器,初始化端口
	public UDPServer(int port) {
		super();
		this.port = port;
	}

	@Override
	public void run() {
		UDPServer uServer=new UDPServer(port);
		uServer.udpServer();
	}
	public void udpServer() {
		//设置socket通信
		DatagramSocket dSocket = null;
		try {
			dSocket = new DatagramSocket(port);
			//接受的字节大小
			byte[] by = new byte[1024];
			//无限监听
			while (true) {
				//定义一个数据包对象
				DatagramPacket dPacket = new DatagramPacket(by, by.length);
				//接受数据包
				dSocket.receive(dPacket);
				//获得数据包中的数据
				byte by1[] = dPacket.getData();
				//获得数据包中数据的长度
				int len = dPacket.getLength();
				//以字符串的形式输出
				System.out.println(dPacket.getAddress() + "对你说:" + new String(by1, 0, len));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dSocket.close();
		}
	}
}

这时,我们需要再定义一个聊天室对象

CharRom

一个客户端

package net;


public class ChatRom implements Runnable {

	@Override
	public void run() {
		//一个客户端
		//发到10000端口,10001端口接受
		Thread thread=new Thread(new UDPClient("192.168.1.44", 10000));
		Thread thread1=new Thread(new UDPServer(10001));
		thread.start();
		thread1.start();
	}
}

另一个客户端

package net;


public class ChatRom implements Runnable {

	@Override
	public void run() {
		//另一个客户端
		//发到10001端口,10000端口接受
		Thread thread=new Thread(new UDPClient("192.168.1.11", 10001));
		Thread thread1=new Thread(new UDPServer(10000));
		thread.start();
		thread1.start();
	}
}

然后分别在两个客户端运行

package net;

public class Chatdemo {
	public static void main(String[] args) {
		ChatRom chatRom=new ChatRom();
		Thread thread=new Thread(chatRom);
		thread.start();
	}
}

好了,聊天室制作完成

总结:

根据UDP特点,发送端和接收端需要线程同时运行,且使用的端口不一样,注意发包的时候和接包的时候编码一致,不然会乱码

 

你可能感兴趣的:(javaj基础)