日期:2014-05-20 浏览次数:20741 次
package cn.edu.usst;
import java.net.*;
public class UDPServer {
private static final int PORT = 50000;
private DatagramSocket dataSocket;
private DatagramPacket dataPacket;
private byte receiveByte[];
public String receiveStr;
//public UDPServer() {
// Init();
//}
public String Init() {
try {
dataSocket = new DatagramSocket(PORT);
receiveByte = new byte[1024];
dataPacket = new DatagramPacket(receiveByte, receiveByte.length);
receiveStr = "";
int i = 0;
while (i == 0)// 无数据,则循环
{
dataSocket.receive(dataPacket);
i = dataPacket.getLength();
// 接收数据
System.out.println("正在接收数据。。。。。。");
if (i > 0) {
// 指定接收到数据的长度,可使接收数据正常显示,开始时很容易忽略这一点
receiveStr = new String(receiveByte, 0, dataPacket.getLength());
System.out.println(receiveStr);
i = 0;// 循环接收
}
}
}
catch (Exception e) {
e.printStackTrace();
//System.out.println("2");
}
finally{
if (dataSocket != null ){
dataSocket.close();
//System.out.println("3");
}
}
return receiveStr;// 返回值,在主函数中等待调用
}
}
package cn.edu.usst;
public class NavigationSystem{
public static void main(String args[]) {
UDPServer udpserver = new UDPServer();
udpserver.Init();
//System.out.println("gpsdata" + UDPServer.receiveStr );
System.out.println("gpsdata" + udpserver.Init() );
}
}
public class NavigationSystem{
public static void main(String args[]) {
UDPServer udpserver = new UDPServer();
Thread t = new Thread(udpserver);//----------------创建并启动线程。
t.start();
String old = "";
String newString = "";
while(true) {//---------------------循环接收数据,如果为空并且不重复,显示。