码迷,mamicode.com
首页 > 编程语言 > 详细

java UDP例子

时间:2018-11-02 15:25:47      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:ring   size   get   generate   serve   tag   通信   bsp   client   

 

 一:服务端

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

public class Server_test {
public static void main(String[] str){
try {
//创建DatagramSocket 对象,并指定该程序的通信端口为10000
DatagramSocket sendDatagramSocket = new DatagramSocket(11111);
//确定要发送的消息
  
String string = " udp Demo";
 

//转成字符数组类型
byte[] by = string.getBytes();
//确定要发送的端口
int port = 1230;
//创建发送类型的数据包,这个数据包包含了要发往的ip地址和端口
DatagramPacket sendPscket = new DatagramPacket(by, by.length,InetAddress.getByName("127.0.0.1"),port);
//通过DatagramSocket 的send方法发送数据
sendDatagramSocket.send(sendPscket);
//创建接收缓冲区
byte[] bt = new byte[1024];
//创建接收类型的数据包

//DatagramPacket(byte[] buf, int length)构造 DatagramPacket,用来接收长度为 length 的数据包

DatagramPacket receivePacket = new DatagramPacket(bt, bt.length);
//通过DatagramSocket 的receive方法发送数据
sendDatagramSocket.receive(receivePacket);
//打印---数据包
String daString = new String(receivePacket.getData(),0,receivePacket.getLength());//getData()方法是返回数据缓冲区
System.out.println(daString);
//关闭接收
sendDatagramSocket.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

 

二:客户端

 

package com.lh.controller;

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

public class Client_test {
public static void main(String[] str){

try {

//确定端口
int port = 1230;
//创建DatagramSocket 对象,并指定该程序的通信端口为8080
DatagramSocket receiveSocket = new DatagramSocket(port);
while(true){
//创建接收缓冲区
byte[] by = new byte[1024];
//创建接收数据包
DatagramPacket receivePacket = new DatagramPacket(by, by.length);
//接收数据
receiveSocket.receive(receivePacket);
//解析消息并打印数据
String string =new String(receivePacket.getData(),0,receivePacket.getLength());
System.out.println(string);
//通过数据包也可以解析ip、和端口,打印
InetAddress ipAddress = receivePacket.getAddress();
int receivePort = receivePacket.getPort();
System.out.println(ipAddress);
System.out.println(receivePort);
//发送数据
String aaString = "123";
byte[] bb = aaString.getBytes();
//创建发送类型的数据包
DatagramPacket sendPscket = new DatagramPacket(bb, bb.length,InetAddress.getByName("127.0.0.1"), 11111);
receiveSocket.send(sendPscket);
}

//receiveSocket.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

java UDP例子

标签:ring   size   get   generate   serve   tag   通信   bsp   client   

原文地址:https://www.cnblogs.com/LinLuMing/p/9896258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!