Java网络编程之UDP通信例子

UDPServer.java

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

/**
 * @description
 * @date:(2015-9-14 下午11:07:55)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
public class UDPServer {
	
	public static void main(String[] args) throws IOException {
		
		//监听8986端口
		DatagramSocket server=new DatagramSocket(8986);
		
		byte[] recvBuf=new byte[1024];
		
		//DatagramPacket(byte[] buf, int length):将数据包中Length长的数据装进Buf数组,一般用来接收客户端发送的数据
		DatagramPacket recvpacket=new DatagramPacket(recvBuf, recvBuf.length);
		
		//receive方法是阻塞式的,知道收到客户端请求才会往下走
		//接收数据报文到recvpacket中
		server.receive(recvpacket);
		
		String recvStr=new String(recvpacket.getData(),0,recvpacket.getLength());
		
		System.out.println("receive from client:"+recvStr);
		
		int port=recvpacket.getPort();//发送端地址
		//发送端地址
		InetAddress addr=recvpacket.getAddress();
		//响应数据
		String response="hello! I'm Server";
	
		byte[] sendBuf=response.getBytes();
		
		//从sendBuf数组中,取出Length长的数据创建数据包对象,目标是clientAddress地址,clientPort端口
		//,通常用来发送数据给客户端。
		DatagramPacket sendpacket=new DatagramPacket(sendBuf, sendBuf.length,addr,port);
		
		//发送报文sendpacket到目的地
		server.send(sendpacket);
		
		server.close();
		
	}

}

Client.java

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

/**
 * @description
 * @date:(2015-9-14 下午11:17:12)
 * @author Administrator
 * @version v1.0
 * @since v1.0
 *
 * Modified history
 *
 *    Modified date:  
 *    Modifier user:     
 *    description: 
 *
 * */
public class Client {
	
	public static void main(String[] args) throws IOException {
		
		DatagramSocket client=new DatagramSocket();
		
		String sendStr="Hello! I'm client";
		
		byte[] sendBuf=sendStr.getBytes();
		
		InetAddress addr=InetAddress.getByName("127.0.0.1");
		
		int port=8986;
		//从Buf数组中,取出Length长的数据创建数据包对象,目标是clientAddress地址,clientPort端口,通常用来发送数据
		DatagramPacket sendpacket=new DatagramPacket(sendBuf, sendBuf.length, addr, port);
		
		//发送报文sendpacket到目的地
		client.send(sendpacket);
		
		byte[] recvBuf=new byte[1024];
		
		DatagramPacket recvPacket=new DatagramPacket(recvBuf,recvBuf.length);
		
		//接收数据报文到recvpacket中
		client.receive(recvPacket);
		
		String recvStr=new String(recvPacket.getData(),0,recvPacket.getLength());
		
		System.out.println("receive from server:"+recvStr);
		
		client.close();
		
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章