UDP协议编程


简单容易的UDP消息发送和接受;UDP是user datagram protocol的简称 户数据包协议,
是 OSI 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。
接下来看代码

server:
 
 public void sendMsg(){
 		int port = 8080;
		String host = "192.168.1.129";
		int length=1500;
		try {
			System.out.println(InetAddress.getByName("localhost"));
			DatagramSocket datasocket = new DatagramSocket();
			byte[] data = "test测试".getBytes("gbk");
			InetAddress address;
			address = InetAddress.getByName(host);
			DatagramPacket pack = new DatagramPacket(data,data.length,address,port);
			datasocket.send(pack);	
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
}

client:
	public static void main(String[] args) {
		byte[] data = new byte[1500];
		int port = 8080;//指定的端口号
		try{
			DatagramSocket socket = new DatagramSocket(port);
			DatagramPacket p = new DatagramPacket(data,data.length);
			socket.receive(p);//接受数据包
			String text = new String(data,0,data.length);
			System.out.println("接受到内容:"+text);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

你可能感兴趣的:(编程,socket)