参考博客:http://blog.csdn.net/wintys/article/details/3525643/,非常感谢
实现功能:客户端发送字符串A ->服务端接收并显示在控制台
服务端回复字符串B ->客户端接收并显示在控制台
服务端程序:
package udpServer; import java.io.*;
import java.net.*; /**
* 服务端
* 1、创建服务+端口
* 2、准备接受容器 byte数组
* 3、把接收容器封装成包 DatagramPacket
* 4、接受数据
* 5、分析数据
*/
public class server { public static void main(String[] args) throws IOException {
DatagramSocket server = new DatagramSocket(5050); byte[] recvBuf = new byte[100];
DatagramPacket recvPacket
= new DatagramPacket(recvBuf , recvBuf.length); server.receive(recvPacket); String recvStr = new String(recvPacket.getData() , 0 , recvPacket.getLength());
System.out.println("接收:\t" + recvStr); int port = recvPacket.getPort();
InetAddress addr = recvPacket.getAddress();
String sendStr = "Hello ! 我是服务器";
byte[] sendBuf;
sendBuf = sendStr.getBytes();
DatagramPacket sendPacket
= new DatagramPacket(sendBuf , sendBuf.length , addr , port ); server.send(sendPacket); server.close();
}
}
客户端程序:
package udpClient; import java.io.*;
import java.net.*; /**
* 1、创建客户端+端口
* 2、准备数据 字节数组
* 3、给数据打包 并指定发送的目的地和端口
* 4、发送
* 5、释放
*
* 思考 : 发送有类型的数据 怎么处理 如对象 数字 等等
*/
public class client {
public static void main(String[] args) throws IOException {
DatagramSocket client = new DatagramSocket(); String sendStr = "我是客户端";
byte[] sendBuf;
sendBuf = sendStr.getBytes();
InetAddress addr = InetAddress.getByName("127.0.0.1");
int port = 5050;
DatagramPacket sendPacket
= new DatagramPacket(sendBuf ,sendBuf.length , addr , port); client.send(sendPacket); byte[] recvBuf = new byte[100];
DatagramPacket recvPacket
= new DatagramPacket(recvBuf , recvBuf.length);
client.receive(recvPacket);
String recvStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
System.out.println("收到: \t" + recvStr); client.close();
} }