JAVA udp 使用示例
说明
udp是面向无连接的通信,优点是短小精悍,速度快;缺点是可能丢包。个人觉得放内网通信,且能容忍丢失请求,是个很好的选择。
接收端
接收端接收到数据包后,根据数据包中的发送者的SocketAddress,给发送者回复信息;DatagramSocket 可接收,可发送,并无服务端和客户端的明细区分。
import java.io.IOException;
import java.net.*;
import java.nio.charset.Charset;
public class UdpReceive {
SocketAddress localAddr = new InetSocketAddress("localhost", 1688);
DatagramSocket udpSocket;
public void receive() {
try {
if (udpSocket == null) {
udpSocket = new DatagramSocket(localAddr);
}
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
udpSocket.receive(packet);
SocketAddress address = packet.getSocketAddress();
String msg = new String(packet.getData(), Charset.defaultCharset()).trim();
System.out.println("receive is:" + msg + " ;" );
byte[] rebuffer = ("hello " + msg).getBytes(Charset.defaultCharset());
DatagramPacket repacket = new DatagramPacket(rebuffer, rebuffer.length,address);
udpSocket.send(repacket);
}
} catch (SocketException e) {
return;
} catch (IOException ex) {
return;
}
}
public static void main(String[] args) {
UdpReceive receive= new UdpReceive ();
receive.receive();
}
发送端
upd是面向无连接的,发送端只管发,不管接收端是否能收到信息;本次发送端代码 还定义了接收线程,用于接收其他发送端发送的数据
import java.io.IOException;
import java.net.*;
import java.nio.charset.Charset;
public class UpdClient {
public UpdClient(){
init();
}
SocketAddress localAddr = new InetSocketAddress("localhost", 1687);
SocketAddress destAdd = new InetSocketAddress("localhost", 1688);
DatagramSocket udpSocket = null;
public void init() {
try {
if (udpSocket == null) {
udpSocket = new DatagramSocket(localAddr);
Thread thread = new Thread(new Receive());
thread.start();
}
} catch (SocketException e) {
return;
}
}
public void send(String data) throws IOException {
byte[] buffer = data.getBytes(Charset.defaultCharset());
send(buffer);
}
public void send(byte[] buffer) throws IOException {
DatagramPacket dp = new DatagramPacket(buffer, buffer.length, destAdd);
udpSocket.send(dp);
}
public class Receive implements Runnable {
@Override
public void run() {
while (true) {
try {
byte[] rebuffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(rebuffer, rebuffer.length);
udpSocket.receive(packet);
SocketAddress address = packet.getSocketAddress();
String msg = new String(packet.getData(), Charset.defaultCharset()).trim();
System.out.println("receive is:" + msg + " ; from:" + address);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws IOException {
UpdClient client = new UpdClient();
byte[] readBuffer = new byte[1024];
while (System.in.read(readBuffer) != -1) {
client.send(readBuffer);
readBuffer = new byte[1024];
}
}
}
演示
启动发送端和接收到,在发送端发送wenjs,接收到接收到信息,且给发送端发送hello wenjs;
发送端控制台
wenjs
receive is:hello wenjs ; from:/127.0.0.1:1688
接收端控制台
receive is:wenjs ;
|