import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Random;import com.action.test.ByteChange;public class IndexAction //extends ActionSupport
{ private static final long serialVersionUID = 4200161034410153742L;
public static void TestUdpPort() {
int myPort=Common.myPort;// 12000;
String yourAddress = Common.yourAddress;//目标IP
int yourPort=Common.yourPort;//10000
//发送内容
// byte[] test1={11,111,111};
// byte[] test1 = { (byte) 0x01, (byte) 0xff, (byte) 0x00, (byte) 0x01,(byte) 0x12, (byte) 0x00, (byte) 0x0a, (byte) 0x00 };
String Str="ff ff 00 01 12 00 0a 00";
DatagramSocket socket = null;
byte[] test1 = Str.getBytes();
String myStr = new String(test1);
try {
socket = new DatagramSocket(myPort);// 12000(ipAddress, port);Common.myPort
final int StartTip[]={12,0,4,8};
final int StartAckTip[]={12,0,4,8};
final String datagramTail="end|";
final String datagramStart="[]08";
            final String datagramStartAck="[]0A";
            int numberRandom=(new Random()).nextInt();
            
DatagramPacket sendPacket=null,receivePacket=null;
        byte sendBuffer[]=new byte[StartTip[0]];
        byte receiveBuffer[]=new byte[StartAckTip[0]];
        //填充开始传输包
        ByteChange.StringToByte(datagramStart, sendBuffer, StartTip[1], 4);
        ByteChange.intToByte(sendBuffer, StartTip[2], numberRandom);
        ByteChange.StringToByte(datagramTail, sendBuffer, StartTip[3], 4);
        //设置超时1ms及初始化数据包
        try{
            socket.setSoTimeout(1);
            sendPacket=new DatagramPacket(test1,test1.length,InetAddress.getByName(yourAddress),yourPort);
            receivePacket=new DatagramPacket(receiveBuffer,receiveBuffer.length);
        }catch(Exception e){}
        boolean canSend=true;
        while(true){
            try{
                if(canSend){
                    socket.send(sendPacket);
                }
                socket.receive(receivePacket);
                //如果接收到数据包,无论如何,下一次都不能发送
                canSend=false;
                //判断标识
                String str=new String(receiveBuffer,StartAckTip[1],4);
                if(!str.equals(datagramStartAck)){
                    continue;
                }
                //判断次随机数
                int num=ByteChange.byteToInt(receiveBuffer, StartAckTip[2]);
                if(num!=numberRandom){
                    continue;
                }
                //否则接收成功,退出循环
                break;
            }catch(Exception e){
                if(e instanceof SocketTimeoutException){
                    canSend=true;
                }
            }
        }
} catch (Exception ex) {
ex.printStackTrace();
}
} /**
 * @param args
 */
public static void main(String[] args) {
TestUdpPort();
}
}import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;import com.action.test.ByteChange;
import com.action.test.ReceiveLittle;
import com.opensymphony.xwork2.ActionSupport;public class Index2Action
{ private static final long serialVersionUID = 4200161034410153742L;  
public static void TestUdpPort() {
DatagramPacket sendPacket=null,receivePacket=null;
String yourAddress = Common.yourAddress;//目标IP
int yourPort=Common.yourPort;// 10000;
DatagramSocket socket;
try {
socket = new DatagramSocket(yourPort);// 10000;,InetAddress.getByName(yourAddress)
//  final int StartTip[]={12,0,4,8}; 
byte[] repBuf = new byte[25];
//         用于发送开始确认包
//        byte sendBuffer[]=new byte[StartAckTip[0]];
        //用于接收开始传输包
//         byte receiveBuffer[]=new byte[StartTip[0]];
        try{
            socket.setSoTimeout(0);
//             String yourAddress=Common.yourAddress; //Common.yourAddress;//"localhost";//"192.168.1.100";
//             int yourPort=Common.myPort; //12000;
//             System.out.println(socket.getLocalSocketAddress()+":"+  socket.getLocalAddress()+""+socket.getInetAddress()+":"+socket.getPort());
//             System.out.println("receiveAddress:"+yourAddress+InetAddress.getByName(yourAddress)+"-->yourPort:"+yourPort);
//             sendPacket=new DatagramPacket(repBuf,repBuf.length,InetAddress.getByName(yourAddress),yourPort);//1
//             sendPacket=new DatagramPacket(repBuf,repBuf.length,InetAddress.getByName(Common.yourAddress),Common.yourPort);
//             sendPacket=new DatagramPacket(repBuf,repBuf.length,InetAddress.getByName(host).getLocalHost(),Common.yourPort);
            receivePacket=new DatagramPacket(repBuf,repBuf.length);
        }catch(Exception e){}
        while(true){
            try {
                socket.receive(receivePacket);
                if(receivePacket!=null&&receivePacket.getData()!=null){
//                  System.out.println(receivePacket.getData());
                 System.out.println(receivePacket.getLength());
System.out.println("#####");
String str="";
byte[] rslt = receivePacket.getData();
for (int i = 0; i < receivePacket.getLength(); i++) {
// System.out.println(rslt[i]);
str+=rslt[i];
}
if(str!=""){
System.out.println(str);
}
System.out.println("#####");
                }
//                //检查标识
//                String str=new String(repBuf,StartTip[1],4);
//                if(!str.equals(datagramStart)){
//                    continue;
//                }
//                //获取次随机数
//                int numberRandom=ByteChange.byteToInt(receiveBuffer, StartTip[2]);
//                sendStartAck(numberRandom);
//                return numberRandom;
            } catch (IOException ex) {
                Logger.getLogger(ReceiveLittle.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();

// catch (UnknownHostException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
} /**
 * @param args
 */
 public static void main(String[] args) {  TestUdpPort();
 }
}package com.action.test;/**
 *
 * @author Administrator
 */
public class ByteChange {
    //将int存入byte数组,使用小端模式
    public static void intToByte(byte b[],int start,int num){
        for(int i=start;i<start+4;i++){
            b[i]=(byte)num;
            num>>>=8;
        }
    }
    //从byte数组中提取int,使用小端模式
    public static int byteToInt(byte b[],int start){
        int num=0;
        for(int i=3+start;i>=start;i--){
            num=num<<8;
            num+=(0xff&(int)b[i]);
        }
        return num;
    }
    //将short存入byte数组,使用小端模式
    public static void shortToByte(byte b[],int start,short num){
        for(int i=start;i<start+2;i++){
            b[i]=(byte)num;
            num>>>=8;
        }
    }
    //从byte数组中提取short,使用小端模式
    public static short byteToShort(byte b[],int start){
        short num=0;
        for(int i=1+start;i>=start;i--){
            num=(short)(num<<8);
            num+=(0xff&(int)b[i]);
        }
        return num;
    }
    //将String填充入数组
    public static void StringToByte(String str,byte b[],int start,int length){
        byte c[]=str.getBytes();
        for(int i=0;i<length;i++){
            b[start+i]=c[i];
        }
    }
    //清空数组
    public static void cleanByte(byte b[]){
        for(int i=0;i<b.length;i++){
            b[i]=0;
        }
    }
    public static void main(String args[]){
        byte buffer[]=new byte[2000];
        for(int i=0;i<1000;i++){
            shortToByte(buffer,i*2,(short)i);
        }
        for(int i=0;i<1000;i++){
            System.out.print(byteToShort(buffer,i*2)+"  ");
            if(i!=0&&i%30==0){
                System.out.println();
            }
        }
    }
}
abstract class Common {
public static String yourAddress="10.9.121.140";//报头IP
// public static String yourAddress="10.9.121.245";//报头IP
public static int myPort=12000;//我的端口
public static int yourPort=10000;//报头端口
}能正常发送数据,就是index2Action收不到报头返回来的数据,到socket.receive(receivePacket);
就卡住不动了大侠们帮我看看,谢了!

解决方案 »

  1.   

    我Index2Action类就是做接收消息的
      

  2.   

    发送一般是不会有问题的,因为它也不会阻塞socket.receive()方法会阻塞直到收到datagram建议把程序先简化一下吧,单纯的收发是很容易到达的
      

  3.   

    报文是什么?udp不都是用报文么
      

  4.   

    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;public class UdpPort { public UdpPort() {
    super(); // TODO Auto-generated constructor stub
    } public void TestUdpPort() {
    String ipAddress = "10.9.121.140";
    String sendStr="ff ff 00 01 12 00 0a 00 00 00"; int port = 10000; DatagramSocket connection = null; byte[] myByte = sendStr.getBytes();
    // String myStr = new String(myByte); try {
     connection = new DatagramSocket(port,InetAddress.getByName(ipAddress));//(ipAddress, port);
    // connection = new DatagramSocket();// (ipAddress, port);port
    // connection.setReceiveTimeout(20*1000);
    connection.setSoTimeout(120 * 1000);
    connection.connect(InetAddress.getByName(ipAddress), port);
    System.out.println("连结创建完成...");
    connection.send((new DatagramPacket(myByte, myByte.length)));
    System.out.println(" 数据发送完成...");
    while (true) {
    byte[] newByte = new byte[4096];
    DatagramPacket dp = new DatagramPacket(newByte, 4096);
    connection.receive(dp);
    if (dp != null && dp.getData() != null) {
    System.out.println(dp.getLength());
    System.out.println("#####");
    byte[] rslt = dp.getData();
    for (int i = 0; i < dp.getLength(); i++) {
    System.out.println(rslt[i]);
    // System.out.println();
    }
    System.out.println("#####");
    }
    // String myDump = buffer.getHexDump(); break;
    }
    connection.close();
    } catch (Exception ex) { ex.printStackTrace(); }
    } /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    UdpPort up = new UdpPort();
    up.TestUdpPort(); }
    }
    我改成这样程序总停在connection.receive(dp);取不到报头返回来的消息,高手都帮帮忙呀
      

  5.   

    我写了个例子,可以运行,先运行sender类再运行reciver类:package com.dsocket;import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;
    import java.net.UnknownHostException;public class Sender { public static void main(String[] args) {

    try {
    while(true){
    String msg = "hello! welcome to DatagramSocket Demo...,";
    DatagramSocket sc = new DatagramSocket();
    DatagramPacket pk = new DatagramPacket(msg.getBytes(), 0, msg.length(), 
    InetAddress.getByName("10.66.78.199"), 8989);
    sc.send(pk);
    sc.close();
    }
    } catch (SocketException e) {
    e.printStackTrace();
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } }}
    package com.dsocket;import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;
    import java.net.UnknownHostException;public class Reciver {

    public static void main(String[] args) {
    try {
    while(true){
    DatagramSocket sc = new DatagramSocket(8989,InetAddress.getLocalHost());
    byte[] b = new byte[1024];
    DatagramPacket pk = new DatagramPacket(b, 1024);
    sc.receive(pk);
    System.out.println(new String(b));
    sc.close();
    }
    } catch (SocketException e) {
    e.printStackTrace();
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
      

  6.   

    哦,哪的port啊,貌似都有啊,port不加,还能过编译?