SOCKET_UDP包的发送及接收

package com.kk.review;

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

public class UDPServer {

public static void main(String[] args) {
UDPServer.receive();
}

static void receive(){
try{
DatagramSocket ds=new DatagramSocket(8890);
byte[] buf=new byte[100];
DatagramPacket dp=new DatagramPacket(buf,100);
ds.receive(dp);
String str=new String(buf,0,dp.getLength());
System.out.println("from client:"+str);
String str1="welcome you!";
DatagramPacket dp1=new DatagramPacket(str1.getBytes(),str1.length(),dp.getAddress(),dp.getPort());
ds.send(dp1);
ds.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
package com.kk.review;

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

public class UDPClient {
public static void main(String[] args) {
UDPClient.send();
}
static void send() {
try{
DatagramSocket ds=new DatagramSocket();
String str="hello udp";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),InetAddress.getLocalHost(),8890);
ds.send(dp);
byte[] buf=new byte[100];
DatagramPacket dp1=new DatagramPacket(buf,100);
ds.receive(dp1);
String str1=new String(buf,0,dp1.getLength());
System.out.println(str1);
       ds.close();
}catch(IOException e){
e.printStackTrace();
}

}
}



你可能感兴趣的:(socket)