网络编程:使用UDP+多线程实现双向交流

发送端和接收端的基本步骤都差不多,加入多线程和循环可以实现多次的接收和发送。

package Net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 接收端
 * 
 * @author zhaoy
 *
 */
public class Test05_receive implements Runnable {
	private DatagramSocket server;

	public Test05_receive(int port) {
		try {
			server = new DatagramSocket(port);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
			byte[] container = new byte[1024 * 60];
			DatagramPacket packet = new DatagramPacket(container, 0, container.length);
			try {
				server.receive(packet);
				byte[] datas = packet.getData();
				int len = packet.getLength();
				String data = new String(datas, 0, len);
				System.out.println(data);
				if (data.equals("bye")) {
					break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		server.close();
	}
}
package Net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 接收端
 * 
 * @author zhaoy
 *
 */
public final class Test05_send implements Runnable {
	private int port;
	private String toIP;
	private int toPort;
	private DatagramSocket client;
	private BufferedReader read;

	public Test05_send(int port, String toIP, int toPort) throws Exception {
		this.toIP = toIP;
		this.toPort = toPort;
		// 使用DatagrameSocket 指定端口 创建发送端
		client = new DatagramSocket(port);
		read = new BufferedReader(new InputStreamReader(System.in));
	}

	@Override
	public void run() {
		while (true) {
			try {
				// 准备数据并转成字节数组
				String data = read.readLine();
				byte[] datas = data.getBytes();
				// 使用DatagramePacket把字节数组封装成数据包
				DatagramPacket packet = new DatagramPacket(datas, datas.length, new InetSocketAddress(toIP, toPort));
				client.send(packet);
				if (data.equals("bye")) {
					System.out.println("send");
					break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		client.close();
	}
}

 

你可能感兴趣的:(随记)