日期:2014-05-18  浏览次数:20636 次

为什么接收到到那么多的?号,而不是发送端传过来的内容?
发送端代码:
package cn.dzr.udp;

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

public class UdpSendDemo
{
public static void main(String[] args) throws IOException
{
/*
 * 1 , 建立udp发送端服务器 (如何建立,使用socket建立)
 * 2, 将要发送的数据打包
 * 3,通过服务端发送数据
 * 4,关闭套接字
 */

//1,建立UDP服务端,
// 直接建立就OK,无需指定连接的地址,
// 无需设置本机的地址??????
System.out.println("发送端启动:.............");
DatagramSocket ds = new DatagramSocket();

//2, 将要发送的数据打包
String str = "UDP SEND TEST!";
byte[] buf = str.getBytes();
DatagramPacket dp = new DatagramPacket(buf,
buf.length, InetAddress.getLocalHost(), 10000);
//发送数据
//要发送到的位置,发送的内容都保存在dp之中..
ds.send(dp);
//发送结束后,关闭套接字。。
ds.close();
}

}


接收端代码:
package cn.dzr.udp;

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

public class UdpReceiveDemo
{
public static void main(String[] args) throws IOException
{
/*
 * 1,建立数据接收端套接字
 * 2.建立数据包用来保存接收数据
 * 3,提取数据
 * 4,显示数据
 * 5,关闭套接字
 */
//1,建立套接字

System.out.println("接收端启动:.............");
DatagramSocket ds = new DatagramSocket(10000,
InetAddress.getLocalHost());
// ds.s
//2,建立保存数据的数据包
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);

//接收数据
ds.receive(dp);
//解析数据并显示
@SuppressWarnings("deprecation")
String text = new String(dp.getData(),dp.getLength());
int port = dp.getPort();
InetAddress address = dp.getAddress();

System.out.println("发送主机地址: "+ address+"\n发动端口:" + port 
+"\n发送内容:"+text);
ds.close();
}
}


服务端启动:.............
发送主机地址: /169.254.207.146
发动端口:56854
发送内容:?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????