UDP传输

import java.net.*;
public class UDPReceDemo
{
public static void main(String args[]){
udpreceMethod2();
}

public static void udpreceMethod2(){
DatagramSocket ds = null;
byte[] buf = new byte[1024];
DatagramPacket packet = null;
InetAddress address = null;
String ip = null;
int port = 0;
try{
ds = new DatagramSocket(9999);
packet = new DatagramPacket(buf,buf.length);
while(true){
ds.receive(packet);
address = packet.getAddress();
ip = address.getHostAddress();
port = packet.getPort();
System.out.println(ip+port+":"+new String(packet.getData(),0,packet.getLength()));
if(new String(packet.getData(),0,packet.getLength()).equals("886"))
break;
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(ds!=null) ds.close();
}catch(Exception e){

}
}
}

public static void udpReceMethod1(){
DatagramSocket ds = null;
try{
ds = new DatagramSocket(9999);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf,buf.length) ;
ds.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(ds!=null) ds.close();
}catch(Exception e){

}
}
}

}



————————————————————————————————————————————————————————————


import java.net.*;
import java.io.*;
public class UDPSendDemo
{
public static void main(String args[]){
udpSendMethod2();
}

public static void udpSendMethod2(){
BufferedReader br = null;
DatagramSocket ds = null;
String inputLine = null;
DatagramPacket packet = null;
try{
InetAddress address = InetAddress.getLocalHost();
br = new BufferedReader(new InputStreamReader(System.in));
ds = new DatagramSocket();
while(true){
inputLine = br.readLine();
packet = new DatagramPacket(inputLine.getBytes(),inputLine.getBytes().length,address,9999);
ds.send(packet);
if("886".equals(inputLine)){
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(br!=null) br.close();
if(ds!=null) ds.close();
}catch(Exception e){

}
}
}

public static void udpSendMethod1(){
DatagramSocket ds = null;
try{
ds = new DatagramSocket();
byte[] buf = "你好".getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 9999);
ds.send(packet);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(ds!=null) ds.close();
}catch(Exception e){

}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值