本帖最后由 陈洋 于 2013-9-24 10:09 编辑
- package cn.itcast.UDP;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- class S implements Runnable{
- @Override
- public void run() {
- try {
-
- DatagramSocket ds = new DatagramSocket(88);
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
-
- String str=null;
- while((str=br.readLine())!=null){
- byte[] buf = str.getBytes();
- DatagramPacket dp = new DatagramPacket(
- buf,buf.length,InetAddress.getByName("192.168.1.101"),10005);
- ds.send(dp);
- }
-
- ds.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
-
- }
- }
- class R implements Runnable{
- @Override
- public void run() {
- try{
-
- DatagramSocket ds = new DatagramSocket(10005);
- while(true){
- byte[] by = new byte[10];
- DatagramPacket dp = new DatagramPacket(by, by.length);
- ds.receive(dp);
-
- System.out.println(new String(dp.getData(),0,by.length));
- }
- ds.close();//这里怎么关闭不了,报错。
- }catch(Exception e){}
- }
- }
- public class UDP2{
- public static void main(String[] args) {
- new Thread(new S()).start();
- new Thread(new R()).start();
-
- }
- }
复制代码 问题在注释处 |