Udp编写一个聊天程序(线程方式)
来源:互联网 发布:r语言数据按组距分组 编辑:程序博客网 时间:2024/06/01 10:22
package com.mth.ChatThread;/* * 发送端 * * */import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;import java.net.UnknownHostException;public class SendThread implements Runnable {private DatagramSocket ds;public SendThread(DatagramSocket ds) {super();this.ds = ds;}@Overridepublic void run() {while (true) {BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;try {while ((line = bufr.readLine()) != null) {if ("886".equals(line)) {break;}byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("127.0.0.1"), 10000);ds.send(dp);}ds.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
package com.mth.ChatThread;/* * 接收端 * * */import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;public class ReceiveThread implements Runnable {private DatagramSocket ds;public ReceiveThread(DatagramSocket ds) {super();this.ds = ds;}@Overridepublic void run() {while (true) {byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);try {ds.receive(dp);String ip = dp.getAddress().getHostName();String str = new String(buf, 0, dp.getLength());int port = dp.getPort();System.out.println(ip + "..." + str + ":" + port);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
测试类:
package com.mth.ChatThread;import java.net.DatagramSocket;/* * 编写一个聊天程序 * 有收数据的部分和发数据的部分 * 这两部分需要同时进行 * 需要用到多线程技术 * 一个线程负责收 一个线程负责发送 * * */public class ChatDemo {/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {DatagramSocket dsSend = new DatagramSocket();DatagramSocket dsRece = new DatagramSocket(10000);new Thread(new SendThread(dsSend)).start();new Thread(new ReceiveThread(dsRece)).start();}}
0 0
- Udp编写一个聊天程序(线程方式)
- C#使用UDP Client编写聊天程序
- C#使用UDP Client编写聊天程序
- 用UDP编写网络聊天程序
- Java使用UDP协议编写聊天程序
- 网络编程与多线程的应用--基于socket udp编写一个简单聊天程序
- 用Delphi编写局域网中的UDP聊天程序 (收藏)
- 黑马程序员-用UDP编写网络聊天程序
- java学习之利用UDP编写网络聊天程序
- 网络编程编写一个聊天程序
- 使用UDP协议编写一个网络程序
- UDP聊天程序
- udp聊天小程序
- UDP聊天程序补充
- UDP聊天程序
- UDP 聊天测试程序
- Java UDP聊天程序
- 【Java】UDP聊天程序
- java利用poi 读写(导入导出)word、excel(数组越界求解决办法)
- Delphi 异常处理详解
- linux重装后
- Ambari安装
- IIS 7 Service Unavailable的解决办法
- Udp编写一个聊天程序(线程方式)
- Nginx学习笔记(五):怎样使用HTTP配置(上)
- JSP中文参数传至JavaBean出现乱码
- UI第二章常用界面软件
- Flex4之元数据标签:[ArrayElementType] [Bindable] [DefaultProperty] [Deprecated] [Embed] 等
- 使用XMing+putty运行linux图形界面程序
- CentOS5.x安装GNOME桌面
- KVO的内部实现
- android使用C/C++调用SO库