欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UDP通信 博客分类: java javaudpsocket 

程序员文章站 2024-03-14 22:34:59
...

服务端:

package s;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Server {
		
	public static void main(String[] args) throws Exception {
		
		DatagramSocket socket = new DatagramSocket(4187);
		System.out.println("启动服务器......");
		byte[] buff = new byte[1024];
		DatagramPacket pack = new DatagramPacket(buff, buff.length);
		socket.receive(pack);
		System.out.println(new String(pack.getData()));
		
		
	}
}

 客户端:

package c;

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


public class Client {
	public static void main(String[] args) throws Exception {
		DatagramSocket data = new DatagramSocket(4187);
		System.out.println("客户端启动......");
		InetAddress inet = InetAddress.getByName("127.0.0.1");
		String str = "hello";
		byte[] buff = str.getBytes();
		DatagramPacket packet = new DatagramPacket(buff, buff.length, inet, 4187);
		data.send(packet);
		
	}
}
 
相关标签: java udp socket