日期:2014-05-20 浏览次数:21078 次
package com.maphao.aisvoyage.ede.xsocket.server; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.maphao.aisvoyage.ede.ServerFactory; import com.maphao.aisvoyage.ede.XServer; import com.maphao.aisvoyage.ede.xsocket.thread.ThreadPool; public class UDPServer implements XServer, Runnable { private static final Log logger = LogFactory.getLog(UDPServer.class); private static int port = 3344; private static int size = 2048; private boolean isStart = true; private static Thread runner = null; private static UDPServer server = null; private static DatagramSocket datagramSocket = null; private static DatagramPacket datagramPacket = null; // private static Thread[] threads = new Thread[10]; //10个线程 private UDPServer() { } public static UDPServer getServer() { if (server == null) { server = new UDPServer(); // for (int i = 0; i < threads.length; i++) { // threads[i] = new Thread(server); // } runner = new Thread(server); byte[] buffer = new byte[size]; try { datagramSocket = new DatagramSocket(ServerFactory.udpPort); } catch (SocketException e) { e.printStackTrace(); } datagramPacket = new DatagramPacket(buffer, buffer.length); } return server; } @Override public void run() { try { logger.debug("UDP server start on " + datagramSocket.getLocalAddress().getHostAddress() + ":" + datagramSocket.getPort()); while (isStart) { datagramSocket.receive(datagramPacket); UDPServerHandler handler = new UDPServerHandler(); handler.onData(datagramPacket); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public void startServer() { isStart = true; runner.start(); // 创建线程,并启动发送 // for (Thread t : threads) { // t = new Thread(server); // t.start(); // } } @Override public void stopServer() { isStart = false; runner.interrupt(); // for (Thread t : threads) { // t = new Thread(server); // t.interrupt(); // } } @Override public void restart() { } public static void main(String[] args) { UDPServer.getServer().startServer(); } }
package com.maphao.aisvoyage.ede.xsocket.server; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.on中