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
原创粉丝点击