udp编程:一对一咨询
2021/7/13 14:07:34
本文主要是介绍udp编程:一对一咨询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.sundear.demo.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; /** * 发送端:使用面向对象封装 */ public class TalkSend implements Runnable{ private DatagramSocket client; private BufferedReader reader; private String toIP; private int toPort; public TalkSend(int port,String toIP,int toPort){ this.toIP=toIP; this.toPort =toPort; try{ client = new DatagramSocket(port); reader = new BufferedReader(new InputStreamReader(System.in)); }catch (SocketException e){ e.printStackTrace(); } } @Override public void run() { while(true) { String data; try { data = reader.readLine(); byte[] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort)); client.send(packet); if(data.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } } }
package com.sundear.demo.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class TalkReceive implements Runnable{ private DatagramSocket server; private String from; public TalkReceive(int port,String from){ this.from= from; try { server = new DatagramSocket(port); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { byte[] container=new byte[1024*60]; while(true) { DatagramPacket packet = new DatagramPacket(container, 0, container.length); try { server.receive(packet); byte[] datas = packet.getData(); String string = new String(datas, 0, packet.getLength()); System.out.println(this.from+":"+string); if(string.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } server.close(); } }
package com.sundear.demo.util; public class TalkStudent { public static void main(String[] args) { new Thread(new TalkSend(7777,"localhost",9999)).start();//发送 new Thread(new TalkReceive(8888,"老师")).start();//接收 } }
package com.sundear.demo.util; public class TalkTeacher { public static void main(String[] args) { new Thread(new TalkReceive(9999,"学生")).start();//接收 new Thread(new TalkSend(5555,"localhost",8888)).start(); } }
老师和学生通过控制台一对一聊天
这篇关于udp编程:一对一咨询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-11cursor试用出现:Too many free trial accounts used on this machine 的解决方法
- 2025-01-11百万架构师第十四课:源码分析:Spring 源码分析:深入分析IOC那些鲜为人知的细节|JavaGuide
- 2025-01-11不得不了解的高效AI办公工具API
- 2025-01-102025 蛇年,J 人直播带货内容审核团队必备的办公软件有哪 6 款?
- 2025-01-10高效运营背后的支柱:文档管理优化指南
- 2025-01-10年末压力山大?试试优化你的文档管理
- 2025-01-10跨部门协作中的进度追踪重要性解析
- 2025-01-10总结 JavaScript 中的变体函数调用方式
- 2025-01-10HR团队如何通过数据驱动提升管理效率?6个策略
- 2025-01-10WBS实战指南:如何一步步构建高效项目管理框架?