从键盘录入数据发送
例:
import java.net.*;
import java.io.*;
class UdpSend2 //发送端
{
public static void main(String[] args)throws IOException
{
DatagramSocket ds = new DatagramSocket(9999);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//键盘录入
String line = null;
while((line=br.readLine()) != null)读取键盘
{
if("886".equals(line))//结束标记
break;
byte[] buf = line.getBytes();//字符变字节
//封装数据包
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("114.98.252.175"), 10001);
ds.send(dp);//发送数据
}
ds.close();
}
}
class UdpRece2 //接收端
{
public static void main(String[] args)throws Exception
{
DatagramSocket ds = new DatagramSocket(10001);
while(true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);//封装数据包
ds.receive(dp);//接收数据
String ip = dp.getAddress().getHostAddress();//接收ip地址
String data = new String(dp.getData(), 0, dp.getLength());//接收数据,并转为字符串
int port = dp.getPort();//接收端口
System.out.println(ip+"..."+data+"..."+port);//输出ip、数据和端口
}
}
}
-----------------------------------------------------------------------------------------------------------------
编写一个聊天程序
有收数据的部分,和发数据的部分
这两个部分需要同时执行
那就需要用到多线程技术
一个线程控制接收,一个线程控制发送
因为收和发动作不是一致的,所以要定义两个run方法。
而且这两个方法要封装到不同的类中
例:
import java.io.*;
import java.net.*;
class Send implements Runnable
{
private DatagramSocket ds;
public Send(DatagramSocket ds)//构造方法
{
this.ds = ds;
}
public void run() //覆盖run方法
{
try
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//键盘录入
String line = null;
while((line=bufr.readLine()) != null) //数据传入
{
if("886".equals(line))
break;
byte[] buf = line.getBytes();//字符数据变为字节
//封装数据包,数据,ip地址,端口
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("114.98.252.175"), 10002);
ds.send(dp);//发送数据
}
}
catch(Exception e)
{
throw new RuntimeException("发送失败");
}
}
}
class Rece implements Runnable
{
private DatagramSocket ds;
public Rece(DatagramSocket ds) //构造方法
{
this.ds = ds;
}
public void run() //覆盖run方法
{
try
{
while(true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length); //封装数据包,内部封装数组
ds.receive(dp); //接收数据
String ip = dp.getAddress().getHostAddress(); //ip地址
String data = new String(dp.getData(), 0, dp.getLength());//数据及长度,并封装字符串对象
System.out.println(ip+"..."+data); //输出ip地址和数据
}
}
catch(Exception e )
{
throw new RuntimeException("接收失败");
}
}
}
class ChatDemo
{
public static void main(String[] args)throws Exception
{
DatagramSocket sendSocket = new DatagramSocket(); //发送端
DatagramSocket receSocket = new DatagramSocket(10002); //接收端,并封装端口号
new Thread(new Send(sendSocket)).start(); //启动发送线程,
new Thread(new Rece(receSocket)).start();
}
}
-------------------------------------------------------------------------------------------------------------------------------
个人总结:从键盘输入的数据要转成字节流,UDP聊天程序要使用两个线程,要处理异常,不能抛