java udp socket 编程

服务器端:

package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Calendar;

public class UdpTimeServerDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		byte[] buffer=new byte[1024];
		DatagramSocket udpServerSocket;
		DatagramPacket udpSendPacket; //发送的包
		DatagramPacket udpReceivePacket;//接收的包
		try {
			udpServerSocket=new DatagramSocket(8000);
			udpReceivePacket=new DatagramPacket(buffer,buffer.length);
			udpServerSocket.receive(udpReceivePacket);
			InetAddress clientAddress = udpReceivePacket.getAddress(); // 得到客户端的地址
			int clientPort=udpReceivePacket.getPort();                 // 得到客户端的端口
			String  s = new String(udpReceivePacket.getData()); 
            System.out.println("客户地址:"+clientAddress
                                               +"  客户端口号:"+clientPort);    
            System.out.println("服务器端收到客户发送数据:"+s);
          //发送数据                
            udpSendPacket = new DatagramPacket(buffer, buffer.length, 
                        clientAddress, clientPort); //设置要发送的数据a
            String msg="已收到连接,你好客户端!";
            udpSendPacket.setData(msg.getBytes());                
            udpServerSocket.send(udpSendPacket); //最后,发送数据包      
            s= new String(udpSendPacket.getData(),0,udpSendPacket.getLength());   
            System.out.println("服务器响应请求:"+s);    
		} catch (IOException ex) {
						ex.printStackTrace();
		}
	}
}


客户端:

package udp;

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 UdpTimeClientDemo {


	public static void main(String[] args) throws IOException {
		byte[] buffer=new byte[1024];
		DatagramSocket udpClientSocket;
		DatagramPacket udpSendPacket;
		DatagramPacket udpReceivePacket;
		InetAddress hostAddress;
		
		try {
			udpClientSocket=new DatagramSocket(3333);
			hostAddress = InetAddress.getByName("localhost");
			udpSendPacket=new DatagramPacket(buffer,buffer.length,hostAddress,8000);
			String s="客户请求连接,你好服务器端!";
			udpSendPacket.setData(s.getBytes());
			udpClientSocket.send(udpSendPacket);
			System.out.println("客户端发送连接请求:"+s);
			udpReceivePacket=new DatagramPacket(buffer,buffer.length,hostAddress,8000);
			udpClientSocket.receive(udpReceivePacket);
			String str=new String(udpReceivePacket.getData());
			System.out.println("客户端接收到服务器端响应:"+str);
		} catch (SocketException e) {
						e.printStackTrace();
		}
		
		
	}

}

你可能感兴趣的:(java,编程,.net,socket)