package com.common.cn;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import opennet.socketserver.client_Daemons.util.IPv4;
public class UDP {
private final int MAX_PORT=65535;
private final int MIN_PORT=0;
private String ip;
private int port;
private DatagramPacket datagramPacket;
protected DatagramSocket serverSocket = null;
/**
* @author Administrator
* @param ip
* @param port
* */
public UDP(String ip, int port) {
super();
this.ip = ip;
this.port = port;
serverSocket =Singleton.getInstance();
}
/**
* @author Administrator
* @param msg for send
*
* */
//发送数据
public void SendMsg(String msg) throws IOException {
byte[] buf = msg.getBytes();
if (this.port <= 0 || this.port>65535) {
System.out.println(“port is out range of ” + this.MIN_PORT +” – “+ this.MAX_PORT);
return;
}
datagramPacket = new DatagramPacket(buf, buf.length,new InetSocketAddress(this.ip, port));
this.serverSocket.send(datagramPacket);
}
//接收数据
private String ReceiveData() throws IOException {
int length = 1500;
byte[] buf = new byte[length];
DatagramPacket dp = new DatagramPacket(buf, length);
this.serverSocket.receive(dp);
byte ipaddrs[] = dp.getAddress().getAddress();
this.ip = IPv4.toIPv4String(ipaddrs);
port = dp.getPort();
String line = new String(dp.getData(), 0, dp.getLength(), “utf-8”);
return line;
}
//关闭连接
private void Close() {
if (this.serverSocket !=null) {
this.serverSocket.close();
this.serverSocket =null;
}
}
}
今天的文章Java UDP封装类分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/25951.html