java,php,asp.net,linux,javascript,mysql,mssql,oracle,编程

UDP程序测试

转载请注明:http://www.pmjava.com/Article/ShowInfo.asp?ID=56593
package com.tz.simple.udp;

import java.io.IOException; import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.tz.uitl.Common;

/**
* UDP程序测试

* 时间服务器,采用线程池处理

*
*
@author LJZ
*
*/
public class UDPTimeServer extends Thread {
   
final private static int DAYTIME_PORT = 7897;

   
private DatagramSocket serverSocket = null;

   
private final int THREAD_POOL = 10;

   
private ExecutorService threadPool = null;

   
public UDPTimeServer() throws IOException {
        serverSocket
= new DatagramSocket(DAYTIME_PORT);
        threadPool
= Executors.newFixedThreadPool(THREAD_POOL);
        System.out.println(
"时间服务器启动成功,监听端口 [" + DAYTIME_PORT + "] 线程池 ["
               
+ THREAD_POOL + "].");
    }

   
public void run() {
       
while (true) {
           
try {
               
byte buffer[] = new byte[256];
                DatagramPacket packet
= new DatagramPacket(buffer,
                        buffer.length);
                serverSocket.receive(packet);
                System.out.println(
"收到客户端 [" + packet.getSocketAddress()
                       
+ " ] 请求.");
                threadPool.execute(
new HandlerThread(packet));
            }
catch (Exception e) {

            }
        }
    }

   
/**
     * 客户端数据处理线程
     *
     *
@author LJZ
     *
    
*/
   
private class HandlerThread extends Thread {
       
private DatagramPacket packet = null;

       
public HandlerThread(DatagramPacket p) {
            packet
= p;
        }

       
public void run() {
           
try {
                String date
= new Date().toString();
               
byte[] buffer = date.getBytes();

                InetAddress address
= packet.getAddress();
               
int port = packet.getPort();
                packet
= new DatagramPacket(buffer, buffer.length, address,
                        port);
                serverSocket.send(packet);

                System.out.println(
"线程 [" + getName() + "] 向客户端 ["
                       
+ packet.getSocketAddress() + " ]  发送数据 ["
                       
+ Common.byte2string(buffer, false) + "].");
            }
catch (Exception e) {

            }
finally {
                packet
= null;
            }
        }
    }

   
public static void main(String args[]) throws IOException {
       
new UDPTimeServer().start();
    }
}

posted on 2009-06-10 21:34 rrong_m 阅读(308) 评论(0)  编辑  收藏

<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

常用链接

随笔档案

文章分类

文章档案

java编程

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜