java UDP 入门

java UDP 入门udp编程相对于tcp编程要简单

udp编程相对于tcp编程要简单一些,主要用到的两个类是,DatagramSocket和DatagramPacket,服务端创建socket,绑定ip和端口,就可以用DatagramPacket接收数据和发送数据,代码如下:

服务器端:

package com.ppt.socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class UDPServer {

	private static String hostname = "127.0.0.1";
	private static int port = 9999;
	public static void main(String[] args) throws Exception {
		SocketAddress bindaddr = new InetSocketAddress(hostname, port);
		DatagramSocket socket = new DatagramSocket(bindaddr);
		byte[] rBuf = new byte[1024];
		DatagramPacket packet = new DatagramPacket(rBuf, 0, rBuf.length);
		socket.receive(packet);
		System.out.println("result: "+new String(rBuf, 0, packet.getLength()));
		rBuf = "hello client".getBytes();
		DatagramPacket send = new DatagramPacket(rBuf, rBuf.length, packet.getAddress(), packet.getPort());
		socket.send(send);
	}

}



客服端:

package com.ppt.socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class UDPClient {

	private static String hostname = "127.0.0.1";
	private static int port = 9999;
	public static void main(String[] args) throws Exception {
		DatagramSocket socket = new DatagramSocket();
		SocketAddress addr = new InetSocketAddress(hostname, port);
		byte[] sBuf = "hello server".getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sBuf, sBuf.length, addr);
		socket.send(sendPacket);
		byte[] rBuf = new byte[1024];
		DatagramPacket rPacket = new DatagramPacket(rBuf, sBuf.length);
		socket.receive(rPacket);
		System.out.println("reuslt: " + new String(rBuf, 0, rPacket.getLength()));
	}

}

今天的文章java UDP 入门分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/26179.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注