MultiThreaded Udp套接字编程

时间:2012-12-21 05:12:42

标签: multithreading udp

这是我的客户端和服务器的代码。

类Client1 {     Client1(int no)     {         尝试         {                 字符串消息;                 message =“你好这是客户”+否;                 byte [] b = message.getBytes();                 DatagramPacket dp = new DatagramPacket(b,b.length,InetAddress.getLocalHost(),3700);                 DatagramSocket sender = new DatagramSocket();                 sender.send(DP);         } catch(例外e)         {             System.out.println(“客户端关闭”);         }     } }

然后我的服务器类是

类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); 
            }
}   

}

然后我的runnable实现是

class 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我得到的是:

启动线程 启动线程 启动线程 在clinet的构造函数2中 java.net.BindException:已在使用的地址:无法绑定 你好,这是客户2

那么有人可以告诉我我做错了吗?

1 个答案:

答案 0 :(得分:0)

不要将客户端绑定到任何特定端口。让实现选择要绑定的可用端口。