【代码积累】UDP client

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


public class UDPClient {
	private static final int TIMEROUT = 5000;
	private static final int MAXNUM = 5;
	private static final int SrcPort = 9000;
	private static final int DstPort = 3000;
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str_send = "I am client!";
		byte[] buf = new byte[1024];
		InetAddress localAddr = null;
		InetAddress remoteAddr = null;
		DatagramSocket dp_socket = null;
		
		//Get local IP,��Ϊ�����أ�����Dst IPҲ�DZ���IP
		try {
			localAddr = InetAddress.getLocalHost();
			remoteAddr = localAddr;
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//Create Send/Receive DatagramPacket
		DatagramPacket dp_send = new DatagramPacket(str_send.getBytes(),str_send.length(),remoteAddr,DstPort);
		DatagramPacket dp_recv = new DatagramPacket(buf,1024);
		
		//Create the send socket
		try {
			dp_socket = new DatagramSocket(SrcPort);
			dp_socket.setSoTimeout(TIMEROUT);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		int tries = 0;
		boolean receivedResp = false;  //�Ƿ���յ�����
		while( ( false == receivedResp ) && ( tries < MAXNUM ) )
		{
			//�ط����ݱ�
			try {
				dp_socket.send(dp_send);
				System.out.println("Sending msg:\r\n"+new String(dp_send.getData()));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//����֮��������
			try {
				dp_socket.receive(dp_recv);
				
				//�ж��Ƿ����Ա��ص�server����Ӧ
				if ( !dp_recv.getAddress().equals(localAddr) )
				{
					throw new IOException("Unknow source address="+dp_recv.getAddress().getHostAddress());
				}
				else
				{
					receivedResp = true;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				tries++;
				System.out.println("More tries...current try="+tries);
				e.printStackTrace();
			}
		}
		
		if ( true == receivedResp )
		{
			String recvMsg = new String(dp_recv.getData());
			System.out.println("Recv:\r\n"+recvMsg);
		}
		else
		{
			System.out.println("No response ,gave up!");
		}
		dp_socket.close();
	}
}

你可能感兴趣的:(【代码积累】UDP client)