简单UDP学习

 

服务端代码
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//服务端
public class Server {

	Log  loger = LogFactory.getLog( Server.class);
	
	private byte[] buffers = new byte[1024];
	
	public static void main(String[] args) {
		Server server = new Server();
		try {
			server.startServer();
		} catch (IOException e) {
			 
			e.printStackTrace();
		}
		
	}
	
	/**
	 * @throws IOException 
	 * 
	 */
	public void startServer() throws IOException{
		InetSocketAddress  iadress = new InetSocketAddress(8812);
		//启动UDP服务器  并给与服务器监听的端口
		DatagramSocket ds = new DatagramSocket( iadress);
	 
		loger.info("服务器启动");
		while(true){
			//阻塞 结束客户端的连接  ,并且创建接收数据包  用来结束客户端传送的数据 
			DatagramPacket packet = new DatagramPacket(buffers,  buffers.length );
			ds.receive( packet);
			String info = new String(packet.getData(),0,packet.getLength());
			loger.info("接收信息::"+info );
			
			loger.info("  来自:"+packet.getAddress()+"  端口:"+packet.getPort());
			
			buffers ="服务器发送的数据:".getBytes();
			//创建数据包 用来发送数据 
			DatagramPacket serverPacket = new DatagramPacket(buffers, buffers.length , packet.getAddress() , packet.getPort());
			//发送数据 
			ds.send( serverPacket);
			System.out.println( "服务端发送数据结束");
		}

	}
	
	
}
  
客户端代码:

package com.UDP;

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

public class UDPClient {

	public static void main(String[] args) {
		
		
		UDPClient udpClient = new UDPClient();
		try {
			udpClient.startClient();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @throws IOException 
	 * 
	 */
	public void startClient() throws IOException{
		//客户端服务   并且给予端口 
		DatagramSocket socket = new DatagramSocket(8899);
		byte[] bs = "客户端发出数据".getBytes();
		InetAddress inet = InetAddress.getByName("127.0.0.1");
		//创建发送数据的数据包 
		DatagramPacket pack = new DatagramPacket(bs,   bs.length,inet ,  8812);
		System.out.println( "将要发送数据!!");
		//发送数据 
		socket.send (pack);
		System.out.println( "客户端数据发送完毕");
		
 
		byte[] buffer = new byte[1024]; 
		//创建接收包 
		DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
		//接收客户端的数据 
		socket.receive(pack);
		
		System.out.println("=====服务器发送到客户端::"+new String(dp.getData()) );
	}
	
}
 

 

 

 

你可能感兴趣的:(java,socket)