26-网络编程-09-网络编程(UDP协议-聊天程序)

来源:互联网 发布:淘宝开店认证在哪里弄? 编辑:程序博客网 时间:2024/06/05 13:27
/* * 利用前面学习的发送端和接收端程序,模拟聊天软件功能 *  * 发现发送和接收是相互独立的,那么采用多线程技术,一个负责发,一个负责接。 */package demo;import java.io.IOException;import java.net.DatagramSocket;public class Chat {public static void main(String[] args) throws IOException {DatagramSocket send = new DatagramSocket();DatagramSocket rece = new DatagramSocket(10000);//接收端必须指定与发送端吻合的端口Send s = new Send(send);Rece r = new Rece(rece);new Thread(s).start();new Thread(r).start();}}/* * 利用cmd窗口演示本程序,打开cmd窗口,进入D盘,进入D:\Java-Eclipse-PersonalFile\vedio26.Internet.09\bin *  * 然后输入命令:java demo.Chat,启动本程序 *  * 随意输入内容,输一次发一次,接一次,直到“886”结束 */

============================分割线======================================

//这里是负责接收端线程的线程任务。package demo;import java.net.DatagramPacket;import java.net.DatagramSocket;public class Rece implements Runnable {private DatagramSocket ds;public Rece(DatagramSocket ds){this.ds = ds;}@Overridepublic void run() {try {while(true){byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String text = new String(dp.getData(),0,dp.getLength());System.out.println(ip+":"+text);if(text.equals("886"))System.out.println(ip+"...退出了聊天室");}} catch (Exception e) {// TODO: handle exception}}}
===========================分割线===========================================

//这里是负责发送端线程的线程任务package demo;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class Send implements Runnable {private DatagramSocket ds;public Send(DatagramSocket ds){this.ds = ds;}@Overridepublic void run() {try {System.out.println("发送端启动......");BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = bufr.readLine())!=null){byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("10.196.19.56"),10000);//这里可以将ip地址最后的56改为255,这样覆盖当前局域网内所有用户,那么可以群聊,即我发送的消息,所有人都能看到ds.send(dp);if("886"==line)break;}ds.close();} catch (Exception e) {// TODO: handle exception}}}



0 0
原创粉丝点击