Java基础—socket—UDP---chatDemo

/**两个线程: * 一个线程控制发数据 * 另一个线程控制收数据 * */

package com.Train;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**两个线程:
 * 一个线程控制发数据
 * 另一个线程控制收数据
 * */

public class ChatDemo {

    public static void main(String[] args) {
        
        try {
            //建立socket
            DatagramSocket sendSok = new DatagramSocket(); 
            DatagramSocket recvSok = new DatagramSocket(10006);
            
            //建立两个类实现Runnable接口
            SendData sd = new SendData();
            RecvData rd = new RecvData();
            //将socket传入线程函数
            sd.sendD(sendSok);
            rd.recvD(recvSok);
            
            //线程开启
            Thread sendThread = new Thread(sd);
            Thread recvThread = new Thread(rd);
            sendThread.start();
            recvThread.start();
            
            
        } catch (SocketException e) { 
            throw new RuntimeException("main程序中错误");
        } 
    } 
} 

class SendData implements Runnable{
    private DatagramSocket ds = null;
    
    public void sendD(DatagramSocket argDs){
        this.ds = argDs;
    }
    public void run() { 
        try { 
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null; 
            while(null!=(line = br.readLine())){ 
                if("886".equals(line))break; 
                DatagramPacket dp = new DatagramPacket(line.getBytes(),line.getBytes().length, InetAddress.getByName("192.168.1.189"), 2000);
                
                this.ds.send(dp);    
            }
        } catch (IOException e) { 
            throw new RuntimeException("发送端错误");
        }  
        ds.close();    
        
    }
}

class RecvData implements Runnable{
    private DatagramSocket ds = null;
    
    public void recvD(DatagramSocket argDs){
        this.ds = argDs;
    }
    
    public void run() { 
        try { 
            while(true){ 
                byte [] bbuf = new byte [1024];
                DatagramPacket dp = new DatagramPacket(bbuf,bbuf.length); 
                
                 this.ds.receive(dp);
                  
                 System.out.println(dp.getAddress().getHostAddress()+":"+dp.getPort()+"\nreceive data: "+new String(dp.getData()));     
            }     
        } catch (Exception e) {
            throw new RuntimeException("接收端错误");
        } 
        
    }
}

<console>:

image

 

网络收发小工具(端口2000):

image

posted @ 2015-07-21 15:08  cuiz_book  阅读(328)  评论(0编辑  收藏  举报