1. 程式人生 > >java UDP例子

java UDP例子

tst trac ipaddr 通過 size static ont con sta

一:服務端

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例子