下面列出了怎么用java.net.DatagramSocket的API类实例代码及写法,或者点击链接到github查看源代码。
public synchronized boolean start(Integer timeout) throws IOException {
if (mThread == null) {
// create a DatagramSocket without binding to any address
mDatagramSocket = new DatagramSocket(null);
mDatagramSocket.setReuseAddress(true);
// bind to any free port
mDatagramSocket.bind(null);
if (timeout != null && timeout > 0) {
mDatagramSocket.setSoTimeout(timeout);
}
mThread = new Thread(this);
mThread.start();
return true;
}
return false;
}
public void run() {
super.run();
while (!this.isExit) {
try {
if (!SessionManager.getInstance().hasSession()) {
try {
UdpConnect udpConnect = new UdpConnect(new DatagramSocket(), this.option, new DataChanel());
udpConnect.startSession();
SessionManager.getInstance().addSession(udpConnect);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
} catch (SocketException e2) {
e2.printStackTrace();
}
}
}
public void SetDevicePwrSaving(DatagramSocket clientSocket, Integer value) throws Exception {
// Only allow this to happen if this device has been bound
if (getIsBound() != Boolean.TRUE) {
return;
}
// Set the values in the HashMap
HashMap<String, Integer> parameters = new HashMap<>();
parameters.put("SvSt", value);
parameters.put("WdSpd", new Integer(0));
parameters.put("Quiet", new Integer(0));
parameters.put("Tur", new Integer(0));
parameters.put("SwhSlp", new Integer(0));
parameters.put("SlpMod", new Integer(0));
ExecuteCommand(clientSocket, parameters);
}
/**
* Full constructor
*/
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
DatagramSocket s, DatagramPacket p,
SnmpMibTree tree, Vector<SnmpMibAgent> m,
InetAddressAcl a,
SnmpPduFactory factory,
SnmpUserDataFactory dataFactory,
MBeanServer f, ObjectName n)
{
super(server, id, f, n);
// Need a reference on SnmpAdaptorServer for getNext & getBulk,
// in case of oid equality (mib overlapping).
//
adaptor = server;
socket = s;
packet = p;
root= tree;
mibs = new Vector<>(m);
subs= new Hashtable<>(mibs.size());
ipacl = a;
pduFactory = factory ;
userDataFactory = dataFactory ;
//thread.start();
}
public PrivateDNSImp(DNSSpoofingIPGetter dnsSpoofingIPGetter) throws Exception {
try {
this.spoofingIp = dnsSpoofingIPGetter;
soc = new DatagramSocket(PORT);
recvPacket = new DatagramPacket(buf, BUFSIZE);
sendPacket = null;
} catch (BindException e) {
util.packetProxyLogErr("cannot boot private DNS server (permission issue or already listened)");
return;
}
s_sAddr = InetAddress.getByName(dnsServer);
s_soc = new DatagramSocket();
s_recvPacket = new DatagramPacket(buf, BUFSIZE);
s_sendPacket = null;
}
@PostConstruct
private void init() {
if (!configBean.contains(ConfigProperties.CLUSTER_BROADCAST_IP)) {
logger.warn("Broadcast IP not configured for node. Clustering will be disabled until an appropriate broadcast IP address is set.");
return;
}
beaconListener = new BeaconListener(this);
beaconListener.start();
try {
host = InetAddress.getByName(configBean.getStringProperty(ConfigProperties.CLUSTER_BROADCAST_IP));
socket = new DatagramSocket();
byte[] buff = configBean.getStringProperty(ConfigProperties.NODE_ID).getBytes();
packet = new DatagramPacket(buff, buff.length, host, ClusterConstants.BEACON_PORT);
broadcastBeacon = true;
broadcastBeaconAlreadyLogged = false;
} catch (UnknownHostException | SocketException ex) {
logger.error("Unable to start node discovery", ex);
}
}
/**
* Full constructor
*/
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
DatagramSocket s, DatagramPacket p,
SnmpMibTree tree, Vector<SnmpMibAgent> m,
InetAddressAcl a,
SnmpPduFactory factory,
SnmpUserDataFactory dataFactory,
MBeanServer f, ObjectName n)
{
super(server, id, f, n);
// Need a reference on SnmpAdaptorServer for getNext & getBulk,
// in case of oid equality (mib overlapping).
//
adaptor = server;
socket = s;
packet = p;
root= tree;
mibs = new Vector<>(m);
subs= new Hashtable<>(mibs.size());
ipacl = a;
pduFactory = factory ;
userDataFactory = dataFactory ;
//thread.start();
}
public void shutdown() {
try {
DatagramSocket clientSocket = new DatagramSocket();
String shutdownSignal = "shutdown";
byte[] sendBuffer = shutdownSignal.getBytes();
DatagramPacket packet =
new DatagramPacket(sendBuffer, sendBuffer.length, new InetSocketAddress("localhost",
port));
clientSocket.send(packet);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
stop = true;
if (thread != null) {
thread.interrupt();
}
}
private void assertSocketActionAfterConnect(DatagramSocket s) throws IOException {
assertEquals(s.getPort(), datagramSocket1Address.getPort());
try {
s.connect(datagramSocket2Address);
fail();
} catch (IllegalStateException expected) {
}
assertTrue(this.channel1.isConnected());
assertTrue(s.isConnected());
// not changed
assertEquals(s.getPort(), datagramSocket1Address.getPort());
s.disconnect();
assertFalse(this.channel1.isConnected());
assertFalse(s.isConnected());
s.close();
assertTrue(s.isClosed());
assertFalse(this.channel1.isOpen());
}
@Override
public void init(DaemonContext context) throws Exception {
System.err.println("Initializing privileged NFS client socket...");
NfsConfiguration conf = new NfsConfiguration();
int clientPort = conf.getInt(NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY,
NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_DEFAULT);
if (clientPort < 1 || clientPort > 1023) {
throw new RuntimeException("Must start privileged NFS server with '" +
NfsConfigKeys.DFS_NFS_REGISTRATION_PORT_KEY + "' configured to a " +
"privileged port.");
}
registrationSocket = new DatagramSocket(
new InetSocketAddress("localhost", clientPort));
registrationSocket.setReuseAddress(true);
args = context.getArguments();
}
private synchronized RTCPReporter startParticipating(DatagramSocket datagramsocket)
throws IOException
{
UDPPacketSender udppacketsender = new UDPPacketSender(datagramsocket);
udpPacketSender = udppacketsender;
if(ttl != 1)
{
udppacketsender.setttl(ttl);
}
// SRIT add for RTP
RTPRawSender rtprawsender = new RTPRawSender(remoteAddress.getDataPort(), remoteAddress.getControlAddress().getHostName(), udppacketsender);
rtpTransmitter = new RTPTransmitter(cache, rtprawsender);
// rtpTransmitter.setSSRCInfo(cache.ourssrc);
// RTCPReporter rtpreporter = new RTCPReporter(cache, rtcpTransmitter);
RTCPRawSender rtcprawsender = new RTCPRawSender(remoteAddress.getControlPort(), remoteAddress.getControlAddress().getHostName(), udppacketsender);
rtcpTransmitter = new RTCPTransmitter(cache, rtcprawsender);
rtcpTransmitter.setSSRCInfo(cache.ourssrc);
RTCPReporter rtcpreporter = new RTCPReporter(cache, rtcpTransmitter);
startedparticipating = true;
return rtcpreporter;
}
public static void closeSilently(Object... xs) {
/// Note: on Android API levels prior to 19 Socket does not implement Closeable
for (Object x : xs) {
if (x != null) {
try {
if (x instanceof Closeable) {
((Closeable) x).close();
} else if (x instanceof Socket) {
((Socket) x).close();
} else if (x instanceof DatagramSocket) {
((DatagramSocket) x).close();
} else {
throw new RuntimeException("cannot close " + x);
}
} catch (Throwable e) {
// TODO : do something ?
}
}
}
}
public static void main(String[] argv) throws Throwable {
if (argv.length > 0) {
System.err.println("This program takes NO command line arguments.");
System.err.println("Set the activity.port property to adjust the port number.");
System.err.println("Set the activity.storage property to set the Storage class to use.");
System.exit(1);
}
int port = Integer.getInteger("activity.port", VAL);
String className = System.getProperty("activity.storage");
if (className == null) {
System.err.println("No Storage class defined via the `activity.storage' property; exiting...");
System.exit(1);
}
Class storageClass = Class.forName(className);
storage = (Storage) storageClass.newInstance();
DatagramSocket socket = new DatagramSocket(port);
byte[] buf = new byte[INT];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
for (;;) {
socket.receive(packet);
byte[] received = new byte[packet.getLength()];
System.arraycopy(packet.getData(), packet.getOffset(), received, 0, packet.getLength());
new ReceiverThread(received).start();
}
}
/**
* Full constructor
*/
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
DatagramSocket s, DatagramPacket p,
SnmpMibTree tree, Vector<SnmpMibAgent> m,
InetAddressAcl a,
SnmpPduFactory factory,
SnmpUserDataFactory dataFactory,
MBeanServer f, ObjectName n)
{
super(server, id, f, n);
// Need a reference on SnmpAdaptorServer for getNext & getBulk,
// in case of oid equality (mib overlapping).
//
adaptor = server;
socket = s;
packet = p;
root= tree;
mibs = new Vector<>(m);
subs= new Hashtable<>(mibs.size());
ipacl = a;
pduFactory = factory ;
userDataFactory = dataFactory ;
//thread.start();
}
/**
* Typical T11
*
* @param _datagramsocket
* @param sSoulissNodeIPAddress
* @param sSoulissNodeIPAddressOnLAN
* @param iIDNodo
* @param iSlot
* @param sOHType
*/
// Parameters sSoulissNode, iSlot, Type and State are stored in the class
public SoulissT11(DatagramSocket _datagramsocket, String sSoulissNodeIPAddressOnLAN, int iIDNodo, int iSlot,
String sOHType) {
super();
this.setSlot(iSlot);
this.setSoulissNodeID(iIDNodo);
this.setType(Constants.Souliss_T11);
// Note is the name of OH Type
this.setNote(sOHType);
}
public static void main(String[] args) throws Exception {
/**
* 准备发送端
* DatagramSocket()
* 构造一个数据报套接字绑定到本地主机机器上的任何可用的端口。
*/
DatagramSocket ds = new DatagramSocket();
/**
* 准备数据包
*1、 DatagramPacket(byte[] buf, int length)
* 构造一个 DatagramPacket length接收数据包的长度
*2、 String的getBytes()
* 方法是得到一个操作系统默认的编码格式的字节数组
*3、 setSocketAddress()
* 设置SocketAddress(通常是IP地址+端口号)都的远程主机发送数据报。
* 4、InetSocketAddress(InetAddress addr, int port)
* 创建一个套接字地址的IP地址和端口号。
*/
String str = "3,19900000001,20171101155915,1,113.26171805987126,23.239234619127426,0.0,192,82|83,WS001,2020051100011002,13570577458";
byte[] ch = str.getBytes();
DatagramPacket dp = new DatagramPacket(ch, ch.length);
dp.setSocketAddress(new InetSocketAddress("127.0.0.1", 4567));
// 发送数据
ds.send(dp);
// 关闭套接字
ds.close();
}
/** {@inheritDoc} */
@Override
public Closeable registerSocket(String name, DatagramSocket socket) {
final ManagedBinding binding = new WrappedManagedDatagramSocket(name, socket, this);
registerBinding(binding);
return binding;
}
protected void init() throws IOException{
DatagramSocket socket = selectable.socket();
if(SO_SNDBUF!=null)
socket.setSendBufferSize(SO_SNDBUF);
if(SO_RCVBUF!=null)
socket.setReceiveBufferSize(SO_RCVBUF);
}
public RTCPRawReceiver(DatagramSocket datagramsocket, OverallStats overallstats, StreamSynch streamsynch)
{
stats = null;
setSource(new UDPPacketReceiver(datagramsocket, 1000));
stats = overallstats;
streamSynch = streamsynch;
}
/**
* Send a command as hexadecimal, e.g.:
* Command recap, using:
* - 1(hex) as command, toggle the output
* - 2(hex) as command, the output move to ON the mode is reset
* - 4(hex) as command, the output move to OFF the mode is reset
* - 8(hex) as command, the mode is set to AUTO
*/
public SoulissT12(DatagramSocket _datagramsocket, String sSoulissNodeIPAddressOnLAN, int iIDNodo, int iSlot,
String sOHType) {
super();
this.setSlot(iSlot);
this.setSoulissNodeID(iIDNodo);
this.setType(Constants.Souliss_T12);
}
public FileLockCommunicator(InetAddressFactory addressFactory) {
this.addressFactory = addressFactory;
try {
socket = new DatagramSocket(0, addressFactory.findLocalBindingAddress());
} catch (SocketException e) {
throw throwAsUncheckedException(e);
}
}
public void run() throws IOException {
InetAddress IPAddress = InetAddress.getByName(host);
byte[] sendData = request.getBytes();
byte[] receiveData = new byte[65535];
// Use the provided socket if there is one, else just make a new one.
DatagramSocket socket = this.clientSocket == null ?
new DatagramSocket() : this.clientSocket;
try {
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, port);
socket.send(sendPacket);
socket.setSoTimeout(500);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
socket.receive(receivePacket);
// Check reply status
XDR xdr = new XDR(Arrays.copyOfRange(receiveData, 0,
receivePacket.getLength()));
RpcReply reply = RpcReply.read(xdr);
if (reply.getState() != RpcReply.ReplyState.MSG_ACCEPTED) {
throw new IOException("Request failed: " + reply.getState());
}
} finally {
// If the client socket was passed in to this UDP client, it's on the
// caller of this UDP client to close that socket.
if (this.clientSocket == null) {
socket.close();
}
}
}
public static void main(String[] args) throws Exception { // 所有异常抛出
String str = "hello World!!!";
DatagramSocket ds = new DatagramSocket(3000); // 服务端在3000端口上等待服务器发送信息
DatagramPacket dp =
new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName("localhost"), 9000); // 所有的信息使用buf保存
System.out.println("发送信息。");
ds.send(dp); // 发送信息出去
ds.close();
}
private boolean createSocket() {
try {
mSocket = new DatagramSocket(new InetSocketAddress(DATAGRAM_PORT));
} catch (SocketException e) {
Log.e(LOG_TAG, "Failed to create socket. Error: " + e.getMessage());
return false;
}
return true;
}
/**
*
* @param socket
*/
public UdpMultiClientServer(DatagramSocket socket) {
super(DatagramSocket.class);
this.socket = socket;
this.port = socket.getLocalPort();
this.address = socket.getLocalAddress();
this.isRunning = new AtomicBoolean(false);
this.name = "UdpMultiClientServer [" + address + ":" + socket.getLocalPort() + "]";
}
public static void main(String args[]) throws Exception {
DatagramSocket s = new DatagramSocket();
int port = s.getLocalPort();
for (int i=0; i<32000; i++) {
try {
DatagramSocket s2 = new DatagramSocket(port);
} catch (BindException e) {
}
}
}
/**
* Constructor
*
* @param program program name
* @param host host where the Rpc server program is started
* @param port port where the Rpc server program is listening to
* @param progNumber program number as defined in RFC 1050
* @param lowProgVersion lowest version of the specification supported
* @param highProgVersion highest version of the specification supported
* @param registrationSocket if not null, use this socket to register
* with portmap daemon
* @param allowInsecurePorts true to allow client connections from
* unprivileged ports, false otherwise
*/
protected RpcProgram(String program, String host, int port, int progNumber,
int lowProgVersion, int highProgVersion,
DatagramSocket registrationSocket, boolean allowInsecurePorts) {
this.program = program;
this.host = host;
this.port = port;
this.progNumber = progNumber;
this.lowProgVersion = lowProgVersion;
this.highProgVersion = highProgVersion;
this.registrationSocket = registrationSocket;
this.allowInsecurePorts = allowInsecurePorts;
LOG.info("Will " + (allowInsecurePorts ? "" : "not ") + "accept client "
+ "connections from unprivileged ports");
}
@Override
public void releaseQuorumChecker(QuorumChecker checker) {
((QuorumCheckerImpl)checker).teardown();
InternalDistributedSystem system = InternalDistributedSystem.getAnyInstance();
if (system == null || !system.isConnected()) {
DatagramSocket sock = (DatagramSocket)checker.getMembershipInfo();
if (sock != null && !sock.isClosed()) {
sock.close();
}
}
}
public static void main(String args[]) throws Exception {
DatagramSocket s = new DatagramSocket();
int port = s.getLocalPort();
for (int i=0; i<32000; i++) {
try {
DatagramSocket s2 = new DatagramSocket(port);
} catch (BindException e) {
}
}
}
/**
* Creates a new instance.
*/
public DefaultDatagramChannelConfig(DatagramChannel channel, DatagramSocket javaSocket) {
super(channel, new FixedRecvByteBufAllocator(2048));
if (javaSocket == null) {
throw new NullPointerException("javaSocket");
}
this.javaSocket = javaSocket;
}