由于此段程序较长, 故选取关键的片断如下, 主要是线程体的问题
socket的构造采用 socket (inetaddress, port ,inetaddress ,port) 的方法,不同的线程
将绑定不同的客户端的端口, 以达到模拟不同用户的目的
//此类调用和设置端口
class clientInfo
{
static private int cPort = 1024;
public synchronized int getPort()
{
return cPort;
}
public synchronized void setPort( int i)
{
cPort +=i;
}
}线程体如下. 
class newClient implements Runnable
{
   
  int sPort = 8080;
  int num;
  clientInfo co;
  int cport =1024;   public   newClient( clientInfo cinfo,int i )
  { co = cinfo ; num = i;}   public  synchronized  void run()
  {
         try{    //服务器端的地址
       InetAddress sinaddr = InetAddress.getByName( "10.1.2.12");
                //客户端的地址
       InetAddress cinaddr = InetAddress.getByName ("10.1.2.21");
                 //取出一个端口
                 int cPort  = co.getPort();
        System.out.println( cPort );
                  co.setPort(1);   //将端口加一
                    // 构造socket
         Socket sock = new Socket (sinaddr,sPort,cinaddr,cPort);                  PrintStream  pin = new PrintStream ( sock.getOutputStream());

                 //以下是对数据的一些封装
                 String ocspreq = "OCSP request";
        OCSPMessage om = new OCSPMessage();
        String ostr = om.PackOCSPRequest( ocspreq, "10.1.2.245");

pin.println(ostr);
System.out.println(ostr);
System.out.println("线程"+num+"工作完毕");
pin.close();
sock.close();
}
catch( Exception e)
{
System.out.println(e.toString());
}
  }
}
为保证port变量的唯一性读取, 顾设置 getPort 和 setPort 方法为 synchronized 上面的代码运行不能通过,  会报出" 连接失败. address in use ...' 的错误
(另外,第一个线程可以连接) , 

解决方案 »

  1.   

    to henry_t:
      我并没有操作别人的机器的端口, 程序中的两个端口分别是服务器端的端口 sPort
    和本级的客户短短口 cPort .  在模拟并发的500各客户端请求时, 我认为每个线程所构造的
    socket 应该绑定不同的客户端cPort。 顾使用了这两个同步方法来获取和设置当前的端口
      

  2.   

      The reason is so simple. When the first thread invoke the run function(), I don't know how you make 500 threads run parallel, the others can't do run(), that's why you see "address in use". 
      You could use the Thread.currentThread to debug the attributes of current thread 
      

  3.   

    to quitejacktus() 
        I know the question too! But I do not know how to solve it. I have tried it many thmods , but I don't succeeded. Could you tell me how I can to solve it?
      

  4.   

      In fact, to simulate parallel threads in one client has no reality meaning. 
      But you could create a thread pool, such as make one thread alive after one special period of time.
      

  5.   

    to quitejacktus:
       是的。我承任实际的应用不大。 但是这个程序是为了检测我的服务是否能够承受至少500个用户同时请求而做的, 您所提到的线程池的方法我会下去一试, 但由于以前并没有这方面的经验
    所以能否请您留下您的email, 以便请教。 其他的朋友如果有什么更好的方法能够实现这种并发请求的测试, 欢迎提出您的意见或看法。