标签:
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(); } }
先启动接受方,然后启动发送方,这样就可以实现一个小小聊天效果,虽然这是在本机上,只要地址和端口对得上,这样就可以实现在线聊天!
标签:
原文地址:http://www.cnblogs.com/sevenlin/p/sevenlin_chatdemo20150801.html