Java UDP网络编程

时间:2022-04-06 20:17:59
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Client {//客户端
public static void main(String[] args) throws Exception {
	Scanner sc = new Scanner(System.in);
	boolean flag=true;
	while(flag){
		Thread.sleep(500);
		DatagramSocket socket = new DatagramSocket();
		System.out.println("请输入:");
		String str=sc.next();
		if(!str.equalsIgnoreCase("over")){
		byte[] buf=str.getBytes();
		DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.1.109"), 4399);
		socket.send(packet);
		socket.close();
		}else{
			System.out.println("聊天结束!");
			flag=false;
		}
		
	}
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;
import java.util.Map;

public class Service {//服务端
static Map<String,String> map=new HashMap<>();
public static void main(String[] args) throws Exception {
	init();//初始化
	DatagramSocket socket = new DatagramSocket(9999);
	byte[] b=new byte[1024];
	DatagramPacket packet = new DatagramPacket(b, b.length);
	while(true){
		socket.receive(packet);
		String ip=packet.getAddress().getHostAddress();
		byte[] data=packet.getData();
		String name=map.get(ip);
		System.out.println(name+"说他大哥:"+new String(b,0,packet.getLength()));
	}
}
public static void init(){
	map.put("192.168.1.110", "狗剩");
	map.put("192.168.1.106", "狗蛋");
	map.put("192.168.1.101", "翠花");
}
}