基于UDP的socket编程
一、步骤
接受端程序编写:
1、调用DatagramSocket(int port)创建一个数据报套接字,并绑定到指定端口上;
2、调用DatagramPacket(byte[] buf, int length),建立一个字节数组以接收UDP包 ;
3、调用DatagramSocket类的receive(),接收UDP包;
4、最后关闭数据报套接字。
发送端程序编写:
1、调用DatagramSocket()创建一个数据报套接字;
2、调用DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port),建立要发送的UDP包;
3、调用DatagramSocket类的send(),发送UDP包;
4、最后关闭数据报套接字。
二、代码实现
Send.java
<span style="font-size:14px;">package Receive2Send;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Send {
public static void main(String[] args) {
// TODO Auto-generated method stub
send();
}
private static void send() {
// TODO Auto-generated method stub
try {
DatagramSocket ds = new DatagramSocket();
String str = "Hello,this is zhangsan";
DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.length(), InetAddress.getByName("localhost"), 6000);
ds.send(dp);
byte[] buf = new byte[100];
DatagramPacket dpRecv = new DatagramPacket(buf, 100);
ds.receive(dpRecv);
System.out.println(new String(buf, 0, dpRecv.getLength()));
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
</span>
Receive.java
<span style="font-size:14px;">package Receive2Send;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Receive {
public static void main(String[] args) {
// TODO Auto-generated method stub
recv();
}
private static void recv() {
// TODO Auto-generated method stub
try {
DatagramSocket ds = new DatagramSocket(6000);
byte[] buf = new byte[100];
DatagramPacket dp = new DatagramPacket(buf, 100);
ds.receive(dp);
System.out.println(new String(buf, 0, dp.getLength()));
String str = "Welcome you!";
DatagramPacket dpSend = new DatagramPacket(str.getBytes(),
str.length(), dp.getAddress(), dp.getPort());
ds.send(dpSend);
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
</span>