码迷,mamicode.com
首页 > 编程语言 > 详细

java scoket (UDP通信模型)简易聊天室

时间:2016-10-17 11:26:54      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 接收线程
 * 
 * @author xiaoduc
 *
 */
public class ReceiveThread extends Thread {

    private DatagramSocket ds;

    public ReceiveThread(int port) {
        super();
        try {
            this.ds = new DatagramSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run() {
        try {
            //创建byte数组
            byte[] buff=new byte[1024];
            //创建一个数据包对象
            DatagramPacket dp=new DatagramPacket(buff, 1024);
            //永真循环
            while(true){
                ds.receive(dp);//接收消息
                String str=new String(dp.getData(),0,dp.getLength());//得到数据
                System.out.println("接收:"+str);//打印消息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ds.close();
        }
    }
}

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * 发送线程类
 * @author xiaoduc
 *
 */
public class SendThread extends Thread{
    private DatagramSocket ds;
    private int sendPort;
    
    public SendThread(int port,int sendPort){
        super();
        this.sendPort=sendPort;
        try {
            this.ds=new DatagramSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void run() {
        try {
            //循环接收用户输入
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String str=null;
            while((str=br.readLine())!=null){
                //创建Datagrampacket对象
                DatagramPacket dp=new DatagramPacket(str.getBytes(), 0,str.length(),InetAddress.getByName("localhost"),sendPort);
                ds.send(dp);//发送数据
                System.out.println("发送:"+str);//打印
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ds.close();
        }
    }
}

 

public class Chat {
    public static void main(String[] args) {
        //启动发送线程
        new SendThread(1091, 1099).start();
        
    }
}

 

public class ReceiveChat {
    public static void main(String[] args) {
        //启动接收线程
        new ReceiveThread(1099).start();
    }
}

 

技术分享

 

java scoket (UDP通信模型)简易聊天室

标签:

原文地址:http://www.cnblogs.com/xiaoduc-org/p/5968921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!