udp程序无法运行

时间:2014-02-04 09:37:46

标签: java networking

我尝试了网络,这是我第一次理解它。我有一个程序与客户端和服务器。我想要做的是服务器应该连续发送数据到一个端口和每当端口中有任何数据说2656时,客户端应该从该端口读取数据,并且应该从端口刷新数据。我已经创建了服务器程序和客户端程序,但是客户端没有收到任何数据包。我是在两台不同的机器上运行客户端和服务器。

服务器程序

import java.io.*;
import java.net.*;

public class Server{
  public static void main(String args[]) throws Exception {
 DatagramSocket dsocket = new DatagramSocket();
    try {
      String host = "192.168.0.15";

    int count =1;
      byte[] message = "Java Source and Support".getBytes();

      // Get the internet address of the specified host
      InetAddress address = InetAddress.getByName(host);

      // Initialize a datagram packet with data and address
for(;;)
{

      DatagramPacket packet = new DatagramPacket(message,   message.length,
          address, 2656);

      // Create a datagram socket, send the packet through it,          //close it.
     System.out.println("Sending data"+message.toString();
      dsocket.send(packet);
}
    } catch (Exception e) {
      System.err.println(e);
    }
    finally
      {
      dsocket.close();
       }
  }
}

客户端程序

package saturdayTest;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPReceive {
  public static void main(String args[]) {
    try {
      int port = 2656;

      // Create a socket to listen on the port.
      DatagramSocket dsocket = new DatagramSocket(port);

      byte[] buffer = new byte[2048];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      while (true) {
         System.out.println("Waiting for  a packer");
        dsocket.receive(packet);

        String msg = new String(buffer, 0, packet.getLength());
        System.out.println(packet.getAddress().getHostName() + ": "
            + msg);


        packet.setLength(buffer.length);
      }
    } catch (Exception e) {
      System.err.println(e);
    }
  }
}

0 个答案:

没有答案