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

java网络编程(4)——udp实现聊天

时间:2015-08-01 00:59:42      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

  UDP可以实现在线聊天功能,我这里就是简单模拟一下:
  发送端:

package com.seven.udp;

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

public class CharByUpdSend implements Runnable {

    private DatagramSocket ds;

    public CharByUpdSend(DatagramSocket ds) {
        this.ds = ds;
    }

    @Override
    public void run() {
        try {
            // 输入
            BufferedReader bufr = new BufferedReader(new InputStreamReader(
                    System.in));

            String line = null;
            while ((line = bufr.readLine()) != null) {

                DatagramPacket dp = new DatagramPacket(line.getBytes(),
                        line.length(), InetAddress.getByName("127.0.0.1"),
                        10001);

                ds.send(dp);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

  接收端:

package com.seven.udp;

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

public class CharByUpdReceive implements Runnable{
    
    private DatagramSocket ds ;
    public CharByUpdReceive(DatagramSocket ds) {
        this.ds = ds;
    }

    
    @Override
    public void run() {
        try{
            while(true){
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                ds.receive(dp);
                String data = new String(dp.getData(),0,dp.getLength());
                System.out.println(dp.getAddress()+"-->"+data);
            }
            
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

 

  主程序:

package com.seven.udp;

import java.net.DatagramSocket;

public class CharDemo {

    
    public static void main(String[] args) throws Exception {
        
        DatagramSocket send = new DatagramSocket();
        DatagramSocket receive = new DatagramSocket(10001);
        
        new Thread(new CharByUpdSend(send)).start();
        new Thread(new CharByUpdReceive(receive)).start();
        
        
    }
}

先启动接受方,然后启动发送方,这样就可以实现一个小小聊天效果,虽然这是在本机上,只要地址和端口对得上,这样就可以实现在线聊天!

java网络编程(4)——udp实现聊天

标签:

原文地址:http://www.cnblogs.com/sevenlin/p/sevenlin_chatdemo20150801.html

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