Udp编写一个聊天程序(线程方式)

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;
	}

	@Override
	public 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 block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.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;
	}

	@Override
	public 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 block
				e.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();

	}
}


你可能感兴趣的:(Socket网络编程)