这段时间做了个小系统:通过建议一个HTTP服务来获取传送到servlet的url里面的参数信息,然后再将信息打包通过UDP协议转发到服务器上面。由于采用的端口是唯一而且固定的,而且利用socket通信的时候要充分考虑到端口占用情况,因此必须解决通信过程中的同步问题。
开始尝试用多线程锁机制来解决问题。由于对锁机制不是太熟悉,因此老是发生第一个线程处理完后无法唤醒其他线程的情况。最后通过单态模式解决了次问题。代码如下:
单态类:Singleton
public class Singleton {
private static Singleton instance;
private DatagramSocket socket;
private String phoneNum;
private String resource;
private String url;
private static int count;
protected Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void set(String phoneNum, String resource, String url) {
this.phoneNum = phoneNum;
this.resource = resource;
this.url = url;
}
public void send() {
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss");
String datetime = f.format(new java.util.Date());
Buildsmp bp = new Buildsmp();
bp.setSmp023("106611331");
bp.setSmp021(this.phoneNum);
String content = "WM#" + this.resource + "#" + this.url;
bp.setSmp032(content);
bp.setSmp060(datetime);
String msg = bp.packSmp();
byte buffer[] = new byte[200];
buffer = msg.getBytes();// 包内容字节化
GetConfig con1 = new GetConfig();
ConfigBean config1 = con1.getConfigInfo();
try {
socket = new DatagramSocket(Integer.parseInt(config1.getPort()));
} catch (NumberFormatException e1) {
e1.printStackTrace();
} catch (SocketException e1) {
e1.printStackTrace();
}
InetAddress ia = null;
try {
ia = InetAddress.getByName(config1.getTarget_ip());
} catch (UnknownHostException e) {
e.printStackTrace();
}
int receive_port = Integer.parseInt(config1.getReceive_port());// 接收端端口
DatagramPacket sent_packet = new DatagramPacket(buffer, buffer.length,
ia, receive_port);// 实例化报文
try {
socket.send(sent_packet);
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
count++;
System.out.println("count = " + count);
}
测试类:Test
public class Test {
private static String mobileNo = "mobileNo";
private static String resourceURL = "resourceURL";
private static String resourceName = "resourceName";
public static void main(String[] args) {
for (int i = 0; i < 1024; i++) {
Singleton s = Singleton.getInstance();
s.set(mobileNo, resourceName, resourceURL);
s.send();
}
}
}
最后:祝贺自己的第一篇原创帖。呼唤大侠给个用线程实现的好例子或者思想,小弟在此谢过