也是好久没写过网络编程,好累,写了一个小时。。。
- /**
-
- */
- import java.net.*;
- import java.io.*;
- class UdpChat{
- public static void main(String [] args)throws Exception{
- DatagramSocket send = new DatagramSocket();
- DatagramSocket rec = new DatagramSocket(10007);
-
- UdpSend us = new UdpSend(send);
- UdpRec ur = new UdpRec(rec);
-
- new Thread(us).start();
- new Thread(ur).start();
- }
- }
- class UdpSend implements Runnable{
- private DatagramSocket ds = null;
- public UdpSend(DatagramSocket ds){
- this.ds = ds;
- }
-
- public void run(){
- try{
- DatagramPacket dp = null;
-
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
-
- String line = null;
-
- byte [] buf = new byte[1024];
-
- while ((line = br.readLine())!=null){
- buf = line.getBytes();
- dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("172.16.8.255"),10007);
- ds.send(dp);
- if(line.equals("over"))
- break;
- }
- ds.close();
- }
- catch(Exception e){
- throw new RuntimeException("rec ex");
- }
- }
- }
- class UdpRec implements Runnable{
- private DatagramSocket ds = null;
- public UdpRec(DatagramSocket ds){
- this.ds = ds;
- }
-
- public void run(){
-
- DatagramPacket dp = null;
-
- byte [] buf = new byte[1024];
-
- try{
- while(true){
- dp = new DatagramPacket(buf,buf.length);
- ds.receive(dp);
-
- String ip = dp.getAddress().getHostAddress();
- int port = dp.getPort();
- String data = new String(dp.getData(),0,dp.getLength()).trim();
- if (data.equals("over")){
- System.out.println("88");
- }
- else {
- System.out.println("receive from:"+ip+".."+"port"+" : "+data);
- }
- }
- }
- catch(Exception e){
- throw new RuntimeException("rec ex");
- }
- }
- }
复制代码
我把close放在finally里抛出SocketException,可是提示我不能抛出,为甚么呢? |
|