菜鸟一枚,简单直接进入主题,想请教各位大神给些建议,好自我更新....................
UDPSocketServer 类模拟服务端,代码:
package com.bzu.udpsocket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;
public class UDPSocketServer {
/**
* 先接收再发送
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
//先接收
DatagramSocket socket=new DatagramSocket(9000);
byte [] buff=new byte[100];
DatagramPacket packet=new DatagramPacket(buff, buff.length);
socket.receive(packet);//接收数据包
System.out.println(new String(buff,0, packet.getLength()));
//返回数据到客户端
System.out.println("请输入回复消息:");
String str=input.nextLine();
DatagramPacket packet2=new DatagramPacket(str.getBytes(), str.length(), packet.getAddress(), packet.getPort());
socket.send(packet2);
socket.close();
}
}
UDPSocketClient类模拟客户端,代码:
package com.bzu.udpsocket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UDPSocketClient {
/**
* 假设本为客户端:先发送,再接收
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Scanner input=new Scanner(System.in);
DatagramSocket socket=new DatagramSocket();//无参,随机生成一个端口号
System.out.println("请输入要发信息:");
String str=input.nextLine();
//封装对象为packet
//参数1:将字符转换成字节.参数2:字符长度.参数3:在给定主机名的情况下确定主机的 IP 地址.参数4:端口号
DatagramPacket packet=new DatagramPacket(
str.getBytes(), str.length(), InetAddress.getByName("localhost"), 9000);
socket.send(packet);//发送数据包
byte [] buff=new byte[100];
DatagramPacket packet2=new DatagramPacket(buff, buff.length);
socket.receive(packet2);//接收数据包
System.out.println(new String(buff,0,packet2.getLength()));
socket.close();
}
}
测试结果如附加图片