java控制台如何实现聊天程序
短信预约 -IT技能 免费直播动态提醒
本篇内容主要讲解“java控制台如何实现聊天程序”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java控制台如何实现聊天程序”吧!
本文实例为大家分享了java控制台实现聊天程序的具体代码,供大家参考,具体内容如下
发送端
package ip.chat;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetSocketAddress;public class TalkSend implements Runnable{ DatagramSocket socket = null; BufferedReader reader = null; private int formIP; private String toIP; private int toPort; public TalkSend(int formIP, String toIP, int toPort) { this.formIP = formIP; this.toIP = toIP; this.toPort = toPort; try { socket = new DatagramSocket(); reader = new BufferedReader(new InputStreamReader(System.in)); }catch (Exception e){ e.printStackTrace(); } } @Override public void run() { while (true){ try { String data = reader.readLine(); byte[] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort)); socket.send(packet); if (data.equals("bye")){ break; } }catch (Exception e){ e.printStackTrace(); } } //关闭 socket.close(); }}
服务端
package ip.chat;import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.SocketException;public class TalkReceive implements Runnable{ DatagramSocket socket = null; private int port; //设置消息来源 private String msgFrom; public TalkReceive(int port ,String msgFrom) { this.port = port; this.msgFrom = msgFrom; try { socket = new DatagramSocket(port); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { while(true){ try { //准备接收包裹 byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,0,container.length); socket.receive(packet);//接收包裹 //断开连接 byte[] data = packet.getData(); String receiveData = new String(data, 0, data.length); System.out.println(msgFrom+":"+receiveData); if (receiveData.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); }}
学生端代码
package ip.chat;public class TalkStudent { public static void main(String[] args) { //开启两个线程 new Thread(new TalkSend(7777,"localhost",9999)).start(); new Thread(new TalkReceive(8888,"老师")).start(); }}
教师端代码
package ip.chat;public class TalkTeacher { public static void main(String[] args) { new Thread(new TalkSend(5555,"localhost",8888)).start(); new Thread(new TalkReceive(9999,"学生")).start(); }}
到此,相信大家对“java控制台如何实现聊天程序”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341