62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.net.*;
public class TestMonitorPort {
public static void main(String[] args) {
for(int i=1025; i<3000; i++) {//使用1024到3000内的UDP端口试试,
printReceiveInfomationFromPort(i);
}
}
static void printReceiveInfomationFromPort(int port) {
new Thread(new MonitorPortRunnable(port)).start();
}
}
class MonitorPortRunnable implements Runnable {
byte buf[] = new byte[1024];
DatagramSocket ds = null;
DatagramPacket dp = null;
int localReceivePort ;
public MonitorPortRunnable(int localReceivePort) {
this.localReceivePort = localReceivePort;
}
public void run() {
dp = new DatagramPacket(buf, 0, 1024);
try {
ds = new DatagramSocket(localReceivePort);
} catch (SocketException e1) {
//prompt("本地接收端口已被使用");
System.exit(0);
}
while (true) {
try {
ds.receive(dp);
System.out.println("信息来自:" + this.localReceivePort);
} catch (IOException e) {
ds.close();
e.printStackTrace();
}
String receiveMessage = new String(dp.getData(), 0, dp
.getLength());
System.out.println(receiveMessage);//暂时打印到控制台,一般输出到文件
}
}
}
/*部分结果:
信息来自:1901
NOTIFY * HTTP/1.1
HOST: 10.10.166.63:1901
SERVER: Windows XP SP3/5.1.2600 IKU/2.1 Center/1.0.1.0
CACHE-CONTROL: max-age=100
LOCATION: http://10.10.166.8:8909/upnp/iKuServices.xml
NTS: ssdp:alive
LAST-UPDATED-TIME: 373
NT: urn:schemas-iku-yoku-com:service:RemoteControl:1
USN: uuid:060b735a-fcac-4466-8909-1fbfb9add62c::urn:schemas-iku-youku-com:service:RemoteControl:1
*/
package yhb;
import java.io.IOException;
import java.net.*;
/*不知道是客户端还是服务器端所以在MAIN方法里只是起了一个处理UDP线程
* */
public class CSDNudp {
public static void main(String[] args)
{
new Thread(new UDPThread()).start();
}
}
class UDPThread implements Runnable {
byte[] buf = new byte[1024];
private int UDP_PORT=9999;
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(UDP_PORT);
} catch (BindException e) {
System.out.println("UDP端口使用中...请重关闭程序启服务器");
} catch (SocketException e) {
e.printStackTrace();
}
/*用这个来处理循环接收数据包比较合理,服务器接收数据包一般都是转发至客户端,而客户端接收数据包一般处理后再发送到服务器,很复杂。不会
close()掉,下面只是简单的System.out.println("收到数据包!")*/
while (ds != null) {
DatagramPacket dp = new DatagramPacket(buf, buf.length);
try {
ds.receive(dp);
System.out.println("收到数据包!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}