import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class UDPClient {
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
DatagramSocket socket=new DatagramSocket(6790);
Scanner input=new Scanner(System.in);
System.out.println("input the string: ");
String str=input.nextLine();
byte[] str1=str.getBytes();
DatagramPacket packet=new DatagramPacket(str1,str1.length,InetAddress.getLocalHost(),6789);
socket.send(packet);
System.out.println("将字符串送至服务器。。。");
Thread.sleep(100);
byte[] buf=new byte[1024];
DatagramPacket packet2=new DatagramPacket(buf,buf.length);
socket.receive(packet2);
byte[] buf2=packet2.getData();
String outstr=new String(buf2,0,packet2.getLength());
System.out.println("从服务器返回结果:"+outstr);
socket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
DatagramSocket server=new DatagramSocket(6789);
byte[] recbuf=new byte[100];
DatagramPacket recvpacket=
new DatagramPacket(recbuf,recbuf.length);
server.receive(recvpacket);
System.out.println("服务器收到数据");
String str1=new String(recvpacket.getData(),0,recvpacket.getLength());
byte[] sendbuf=str1.toUpperCase().getBytes();
DatagramPacket send=new DatagramPacket(sendbuf,sendbuf.length,InetAddress.getLocalHost(),6790);
server.send(send);
server.close();
}
}