network 多线程聊天

来源:互联网 发布:nosql和sql有什么不同 编辑:程序博客网 时间:2024/06/04 19:11
/*多线程聊天工具有收数据的部分,和发数据的部分。这两部分需要时执行。那就需要用到多线程技术。一个线程控制收,一个线程控制发。因为收和发动作是不一至的,所以要定义两个run方法。而且这两个方法要封装到不同的类中。*/package com;import java.net.*;import java.io.*;class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds){this.ds = ds;}public void run(){try{BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = br.readLine()) != null){if("886".equals(line))break;DatagramPacket dp = new DatagramPacket(line.getBytes(),line.length(),InetAddress.getLocalHost(),8888);ds.send(dp);}}catch (Exception e){System.out.println("数据发送失败!");}}}//多线程接收端class Rec implements Runnable{private DatagramSocket ds;public Rec(DatagramSocket ds){this.ds = ds;}public void run(){try{while(true){byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf,buf.length);ds.receive(dp);//收到数据//显示对方IP及发送的信息System.out.println("收到主机:"+dp.getAddress().getHostName()+"...发来的信息:"+new String(buf,0,dp.getLength()));}}catch (Exception e){System.out.println("数据发送失败!");}}}public class  Send_Rec{public static void main(String[] args) throws Exception{DatagramSocket sends = new DatagramSocket();DatagramSocket recds = new DatagramSocket(8888);Send send = new Send(sends);Rec rec = new Rec(recds);new Thread(send).start();new Thread(rec).start();}}

0 0
原创粉丝点击