下面是獨立的兩個類,為了程序的完整性我全部貼了出來,其實問題只是針對一個語句
- public class UdpRecDemo2 {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- while (true) {
- DatagramSocket ds = new DatagramSocket(10001);//這句話爲什麽不能寫在循環內,運行時會報錯.
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf, buf.length);
- ds.receive(dp);
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(), 0, dp.getLength());
- System.out.println(ip + ":" + data);
- }
- }
- }
- public class UdpSendDemo2 {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // TODO Auto-generated method stub
- DatagramSocket ds = new DatagramSocket();
- BufferedReader bufr = new BufferedReader(new InputStreamReader(
- System.in));
- String line = null;
- while ((line = bufr.readLine()) != null) {
- if ("over".equals(line)) {
- break;
- }
- byte[] buf = line.getBytes();
- DatagramPacket dp = new DatagramPacket(buf, buf.length,
- InetAddress.getByName("192.168.1.114"), 10001);
- ds.send(dp);
- }
- ds.close();
- }
- }
复制代码 |