2012-12-21 149 views
0

這是我的客戶端和服務器的代碼。多線程Udp套接字編程

類客戶端1 { 客戶端1(INT否) { 嘗試 { 字符串消息; message =「你好,這是客戶端」+不; byte [] b = message.getBytes(); DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getLocalHost(),3700); DatagramSocket sender = new DatagramSocket(); sender.send(dp); (例外e) { System.out.println(「client shutdown」); } } }

然後我的服務器類是

類Server1的 {

int cnt=0; 
String s1; 
Server1() 
{ 

    try { 
      byte[] buffer = new byte[65536]; 
      DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); 
      DatagramSocket ds = new DatagramSocket(3700); 
      ds.receive(incoming); 
      byte[] data = incoming.getData(); 
      String s = new String(data, 0, incoming.getLength()); 
      System.out.println("Port" + incoming.getPort() + " on " + incoming.getAddress() + " sent this message:"); 

      System.out.println(s.toUpperCase()); 
      } 

      catch (IOException e) 
      { 
      System.err.println(e); 
      } 
} 

}

然後我可以運行實現

類prothread實現Runnable {

//long time=0; 
    //int portno; 
    int flag=0; // this is to differentiate between a server and client 
    private String capitalizedSentence; 
prothread(long l) 
{ 
    if(l==1) 
     { // it is a server 
      flag=1; 
     } 
     else 
     { 
      flag=(int) l; 
     } 
} 

@Override 
public void run(){ 
    // TODO Auto-generated method stub 

     System.out.println("Starting thread");  
     if(flag==1)// Code for server 
      { 
      Server1 s=new Server1(); 

      } 
      else // code for client 
      {     
       Client1 c=new Client1(flag); 

      } 

    } 

}

最後其部署此客戶端和服務器類是

公共類Samplepro31 {

public static void main(String[] args) { 
    // First i'm going to create a server and then clients for it 
     int i=1; 
     int cnt=0; 

     prothread[] p; 
     Thread[] th; 
     Random r =new Random(); 
     // Array has been declared 
     p=new prothread[10];// Memory allocated to it 
     th= new Thread[1000]; 
     p[0]=new prothread(1); 
     cnt=1; 
     //p[0].setportno(cnt); 
     th[0]=new Thread(p[0]); 
     th[0].start(); 
     while(cnt<3) 
     { 

       p[cnt]=new prothread(cnt); 
       // here send the port number 
       th[cnt]=new Thread(p[cnt]); 
       //p[cnt1].setportno(cnt1); 
       th[cnt].start(); 
       cnt++; 
     } 

    } 

}

所以問題我有一臺服務器並且只有一個客戶端在運行 而不是2個客戶端應該運行o/p我是得到的是:

啓動線程 啓動線程 啓動線程 內部客戶爲例的構造函數2 java.net.BindException:使用地址已:無法綁定 HELLO THIS IS CLIENT 2

那麼有誰能夠告訴我什麼我做錯了?

回答

0

不要將客戶端綁定到任何特定端口。讓實現選擇一個可用端口進行綁定。