19. 17. 1. UDP客户端响应 UDP Echo Client

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.SocketException;
public class UDPEchoClient{
	public static void main(String[] args) throws Exception{
		String hostName = "localhost";
		InetAddress addr = InetAddress.getByName(hostName);
		SenderThread sender = new SenderThread(addr, 8080);
		sender.start();
		Thread receiver = new ReceiverThread(sender.getSocket());
		receiver.start();
	}
}

class SenderThread extends Thread{
	private InetAddress server;// (IP) 地址。
	private DatagramSocket socket;//用来发送和接收数据报包的套接字
	private boolean stopped = false;//一开始为不停止
	private int port;//端口
	
	public SenderThread(InetAddress address, int port) throws Exception{//它的构造方法
		this.server = address;
		this.port = port;
		this.socket = new DatagramSocket();
		this.socket.connect(server, port);
	}
	public void halt(){//halt:停止、止步  一个方法
		this.stopped = true;
	}
	public DatagramSocket getSocket(){//Datagram:n. 数据电报  返回父类的socket
		return this.socket;
	}
	public void run(){
		try{
			//用户输入
			BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
			while(true){//死循环
				if(stopped){
					return ;
				}
				String line = userInput.readLine();//把输入的给line
				if(line.equals(".")){//遇到"."跳过
					break;
				}
				byte[] data = line.getBytes();//获得line的数组给data
				
				//构造数据报包(data-包数据,data.lenght-包长度,server-目的地址,port-端口号)
				DatagramPacket output = new DatagramPacket(data, data.length, server, port);
				socket.send(output);//发送出去
				Thread.yield();//yield:n. 产量;收益 --暂停当前正在执行的线程对象,并执行其他线程。
			}
			
		}catch(IOException e){
			System.out.println(e);
		}
	}
	
	
}

class ReceiverThread extends Thread{
	DatagramSocket socket;
	private boolean stopped = false;
	public ReceiverThread(DatagramSocket ds) throws Exception{
		this.socket = ds;
	}
	public void halt(){//停止的方法
		this.stopped = true;
	}
	
	public void run(){
		byte[] buffer = new byte[65507];
		while(true){
			if(stopped){
				return;
			}
			DatagramPacket dp = new DatagramPacket(buffer, buffer.length);//用来接收长度为 length 的数据包
			try{
				socket.receive(dp);//接收数据包
				String s = new String(dp.getData(), 0, dp.getLength());
				System.out.println(s);
				Thread.yield();
			}catch(IOException e){
				System.out.println(e);
			}
		}
	}
}


你可能感兴趣的:(thread,exception,String,Class,byte,output)