用Java语言编写简单聊天程序

来源:互联网 发布:linux 统计大文件行数 编辑:程序博客网 时间:2024/05/18 03:08
<span style="font-size:18px;"></span><pre name="code" class="java"><span style="font-size:18px;">Tips:编写一个聊天程序。传输层使用UDP协议。可以同时接收、发送数据 需要多线程技术一个线程控制接收,一个线程发送 因为收和发动作不一致,定义两个run方法这两个方法封装在不同的类中 </span>
<span style="font-size:18px;">import java.io.*;import java.net.*;/* * 创建局域网聊天 */public class UDPChat{public static void main(String[] arr) throws Exception{DatagramSocket sendsocket = new DatagramSocket();DatagramSocket recesocket = new DatagramSocket(10239);new Thread(new UDPSendChat(sendsocket)).start();new Thread(new UDPReceChat(recesocket)).start();}}class UDPSendChat implements Runnable {private DatagramSocket ds;public UDPSendChat(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {try {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = br.readLine())!=null){//read阻塞式方法if("886".equals(line))break;byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getLocalHost(), 10239);ds.send(dp);}} catch (Exception e) {throw new RuntimeException("发送失败");}} }class UDPReceChat implements Runnable {private DatagramSocket ds;public UDPReceChat(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 data = new String(dp.getData(),0,dp.getLength());        System.out.println(ip+"..."+data);     }} catch (Exception e) {throw new RuntimeException("接受失败");}}}</span>
<span style="font-size:18px;">不同的IP地址上聊天截图:</span>
<span style="font-size:18px;"><img src="http://img.blog.csdn.net/20160618105059608?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></span>
<span style="font-size:18px;"><img src="http://img.blog.csdn.net/20160618105104139?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /></span>
<span style="font-size:18px;"></span>
<span style="font-size:18px;"></span>
0 0
原创粉丝点击