毕向东udp学习笔记2

时间:2021-06-01 20:21:08

项目功能:

 发送端读取控制台输入,然后udp发送

接收端一直接收,直到输入为886

相对于笔记1,修改了发送端代码,实现发送控制台的内容,接收端循环接收,当输入886时,停止发送

发送端:

import java.net.*;
import java.io.*; public class udpSend2
{
/*
*记得抛异常
*/
public static void main(String[] args) throws IOException{ System.out.println("发送端启动...");
/*
*创建UDP传输的发送端
* 思路:
* 1.建立udp的socket服务(new socket)
* 2,将要发送的数据封装到数据包中。(packet)
* 3,通过udp的socket服务将数据包发送出去(send)
* 4,关闭socket服务(close) **抛一个大异常:IOException
*/ //1.udpsocket服务对象,使用DatagramSocket创建,可以指明本地IP和端口
DatagramSocket ds = new DatagramSocket(8888); //2.将要发送的数据封装到数据包中
//String str ="udp传输,哥们,我是客户端";
//使用控制台输入
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line =null; while((line=bufr.readLine())!=null){ byte[] buf =line.getBytes();
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.103"),10000); ds.send(dp);
//如果输入内容是"886",跳出循环
if("886".equals(line))
break;
} //4.关闭连接
ds.close(); }
}

接收端:

 import java.net.*;
import java.io.*; public class udpRecv2
{
/*
* 创建UDP传输的接收端
* 1.建立udp socket服务,因为是要接收数据,必须指明端口号
* 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法处理数据
* 3,使用socket服务的receive方法将接收的数据存储到数据包中
* 4,通过数据包的方法解析数据包中的数据
* 5,关闭资源 *抛一个大异常:IOException
*/
public static void main(String[] args) throws IOException{
//1,创建udp socket服务
DatagramSocket ds = new DatagramSocket(10000);
//一直循环接收,直到886时退出(注意:ds的创建必须写在循环外面)
while(true)
{
//2,创建数据包
byte[] buf =new byte[1024];
DatagramPacket dp =new DatagramPacket(buf,buf.length); //3,使用接收的方法将数据包存储到数据包中
ds.receive(dp);//阻塞式 //4.通过数据包对象的方法,解析其中的数据,比如端口,地址,内容等
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String content = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::" +port+":"+content);
if(content.equals("886")){
System.out.println(ip+"退出聊天室");
break;
} }
//5关闭资源
ds.close(); }
}

效果:

发送端:

毕向东udp学习笔记2

接收:

毕向东udp学习笔记2