package Test_UDP_Socket;
import java.net.DatagramPacket、*
//服务器端
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ServerUDP {
public static void main(String[] args) throws Exception{
//1.先实现接收Client信息
DatagramSocket socketServer= new DatagramSocket(9090);
byte[] data=new byte[1024];
DatagramPacket packetClient=new DatagramPacket(data,data.length);
socketServer.receive(packetClient);
//String infoClient=new String(data,0,packetClient.getLength());
System.out.println("[SERVER]Server IP Address:"+InetAddress.getLocalHost());
System.out.println("[SERVER]Information from Client:\n"+(new String(data,0,packetClient.getLength())));
//2.然后实现Server给Client的一个响应信息;应该包括(端口号;IP地址;还有一个响应请求数据)
byte[] dataServer="[SERVER]:Welcome!".getBytes();
DatagramPacket packetServer;
packetServer=new DatagramPacket(dataServer,dataServer.length,packetClient.getAddress(),packetClient.getPort());
DatagramSocket socketClient=new DatagramSocket();
socketServer.send(packetServer);
//3.关闭资源:
socketServer.close();
}
}
//客户端我们也这样写
package Test_UDP_Socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ClientUDP {
public static void main(String[] args) throws IOException{
//1.实现给Client端给服务器发送登录请求信息
byte[] dataClient="[CLIENT]:UserName:WXM PassWord:123".getBytes();
DatagramPacket packetClient=new DatagramPacket
(dataClient,dataClient.length,InetAddress.getByName("localhost"),9090);
DatagramSocket socketClient=new DatagramSocket();
socketClient.send(packetClient);
//2.实现接收Server端的响应信息
byte[] dataServer=new byte[1024];
DatagramPacket packetServer;
packetServer=new DatagramPacket(dataServer,dataServer.length);
socketClient.receive(packetServer);
//String infoServer=new String(dataServer,0,packetServer.getLength());
System.out.println("[CLIENT]:Information from Server:\n"+
(new String(dataServer,0,packetServer.getLength())));
//3.关闭资源
socketClient.close();
}
}
/*
基于UDP的SOCKET网络编程主要需要写两个模块
客户端请求和服务器响应的发送
关闭资源
转载于:https://blog.51cto.com/10901776/1727589