JAVA 网络编程之UDP(用户数据包协议)

 

/**服务器**/

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



public class ChatterServer {

	public static final int INPORT = 1711;//服务器端口
	private byte[] buf = new byte[1000];
	private DatagramPacket packet = new DatagramPacket(buf, buf.length);//创建数据包
	private DatagramSocket socket;//UDP套接字
	public ChatterServer(){
		try{
			socket = new DatagramSocket(INPORT);//启动套接字
			System.out.println("Server started");
			while(true){
				socket.receive(packet);//接收数据包并将当前线程挂起
				String rcvd = Datagram.toString(packet) + ", from adddress:" + packet.getAddress() + ",port:" + packet.getPort();//解析数据包
				System.err.println(rcvd);//打印数据信息
				String echoString = "Echoed:" + rcvd;
				DatagramPacket echo = Datagram.toDatagram(echoString, packet.getAddress(), packet.getPort());//将接收到包重新包装称UDP数据包准备原封不动的返回给客户端
				socket.send(echo);//反馈数据包
			}
		}catch (SocketException e) {
			System.out.println("Can`t open socket");
			System.exit(1);
		}catch (IOException e) {
			System.out.println("Communication error");
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		new ChatterServer();//运行服务器
	}
}

/**客户端**/

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


public class ChatterClient extends Thread {

	private DatagramSocket socket;
	private InetAddress address;
	private byte[] buf = new byte[1000];
	private DatagramPacket packet = new DatagramPacket(buf, buf.length);//创建要发送的数据包
	private int id;//客户端id

	public ChatterClient(int id) {
		this.id = id;
		try {
			socket = new DatagramSocket();//创建UDP套接字
			address = InetAddress.getByName(null);//取得本地地址
		} catch (SocketException e) {
			System.out.println("can not open socket");
			e.printStackTrace();
			System.exit(1);
		} catch (UnknownHostException e) {
			System.out.println("Can not find host");
			System.exit(1);
		}
		System.out.println("ChatterClient starting");
		start();//之后调用run()
	}
	
	public void run(){
		try {
			for(int i = 0 ; i < 25 ; i++){
				String outMsg = "Client #" + id + ",message #" + i;//要发送到服务器的数据
				socket.send(Datagram.toDatagram(outMsg, address, ChatterServer.INPORT));//打包数据并将其发送到指定地址+端口的服务端
				socket.receive(packet);//接收服务端返回的数据包
				String rcvd = "Client #" + id +", rcvd from " + packet.getAddress() + "," + packet.getPort() + ":" + Datagram.toString(packet);//整合返回信息
				System.out.println(rcvd);//输出到控制台
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);//出错退出
		}
	}
	
	public static void main(String[] args) {
		for(int i = 0 ; i < 10 ; i ++ ){
			new ChatterClient(i);
		}
	}
}

你可能感兴趣的:(java)