java 简单socket实现udp通信

java实现socket通信

学会了一个eclipse快捷键:Ctrl+Shift+M,快速导入所缺的包名
创建DatagramSocket和DatagramPacket对象
填好参数,send(packet),receive(packet)
还是比较简单的

发送类:

package study;

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

public class Socket {
	public static void main(String[] args) throws Exception {//throws Exception表示抛出异常
		String str = "what are you 弄啥嘞";
		DatagramSocket socket = new DatagramSocket();
		DatagramPacket packet = new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("192.168.1.102"), 8888);
		socket.send(packet);
		socket.close();
	}
}

接收类:

package study;

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

public class Socket_Sever {

	public static void main(String[] args) throws Exception {
		DatagramSocket socket = new DatagramSocket(8888);//端口为8888
		DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
		socket.receive(packet);
		
		byte[] arr = packet.getData();
		int len = packet.getLength();
		System.out.println(new String(arr,0,len));
		socket.close();
	}
}

测试完美
java 简单socket实现udp通信_第1张图片

你可能感兴趣的:(java 简单socket实现udp通信)