DatagramSocket

The client part.

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

public class UDPsend {

	/**
	 * direction: This is a client. The process has used UDP protocol. The code
	 * is a example to tell us how to build connection to server and send
	 * message.
	 * 
	 * (1)We should create a DatagramSocket object and specify the value of
	 * 	  itself port. which is also called build UDP connection. 
	 * (2)We should make a packet which has some information about data, length,IP and server port
	 * (3)Sends your packet.
	 * 
	 */
	public static void main(String[] args) throws IOException {

		DatagramSocket s = new DatagramSocket(8888);
		String str = "Welcome to Shandong Normal University";
		byte[] buf = str.getBytes();
		DatagramPacket packet = new DatagramPacket(buf, buf.length,
				InetAddress.getByName("127.0.0.1"), 10000);
		s.send(packet);
	}

}



The server part.

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

public class UDPreceive {

	/**
	 * directions:
	 * This is a server, you can receive message from a client.
	 * 
	 * (1)Building UDP connection.
	 * (2)Prepares a packet for receive a message.
	 * (3)Receive.
	 * (4)We can use the packet we has received to get IP,Port and message.
	 *  
	 */
	public static void main(String[] args) throws IOException {

		DatagramSocket s = new DatagramSocket(10000);
		byte[] buf = new byte[100];

		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		s.receive(packet);

		byte[] data = packet.getData();
		String str = new String(data, 0, packet.getLength());

		String hostadd = packet.getAddress().getHostAddress();
		int port = packet.getPort();
		System.out.print("HostAddress:" + hostadd + ",Port:" + port + ",信息:"
				+ str);
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值