本帖最后由 何羡玉 于 2013-5-4 15:10 编辑
我的这个程序是UDP发送端和接收端的。我想实现发送端和接收端都可以有发送和接收的功能。而且不受发送和接收顺序的限制。我把发送和接收分别封装在两个线程里,可是线程创建不成功。这是怎么回事呢
package sockedTest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.*;
public class udpChatr {
public static void main(String[] args) throws IOException {
InetAddress ia=InetAddress.getLocalHost();
DatagramSocket ds=new DatagramSocket(55599); //监听55599端口
while(true){
BufferedInputStream bufi=new BufferedInputStream(System.in);
/**byte[] br=new byte[1024*2];
DatagramPacket dpr=new DatagramPacket(br,br.length);
ds.receive(dpr);
System.out.println(new String (dpr.getData(),0,dpr.getLength()));
*/
/**
byte[] b=new byte[1024*2];
BufferedInputStream bufi=new BufferedInputStream(System.in);//从键盘读入,用来发送的
int len=bufi.read(b);
DatagramPacket dps=new DatagramPacket(b,len,ia,55598);
ds.send(dps);
}*/
new threadr(ds).start(); //一旦连接了就开启接收的线程,接收对方发来的信息
new threads(ds,ia,bufi).start(); //开启发送的线程,开启了之后就可以发送信息
//ds.close();
}
}
class threadr extends Thread //负责接收的线程
{
private DatagramSocket ds;
threadr(DatagramSocket ds)
{
this.ds=ds;
}
public void run()
{
try{
byte[] br=new byte[1024*2];
DatagramPacket dpr=new DatagramPacket(br,br.length);
ds.receive(dpr);
System.out.println(new String (dpr.getData(),0,dpr.getLength()));
}
catch(Exception e)
{
System.out.println("出错了。。。。。 亲");
}
}
}
class threads extends Thread //负责发送的线程
{
private InetAddress ia;
private DatagramSocket ds;
private BufferedInputStream bufi;
threads(DatagramSocket ds,InetAddress ia,BufferedInputStream bufi)
{
this.ds=ds;
this.ia=ia;
this.bufi=bufi;
}
public void run()
{
try{
byte[] b=new byte[1024*2];
int len=bufi.read(b);
DatagramPacket dps=new DatagramPacket(b,len,ia,55598);//这个数据包发送到的55598端口,即目的地
ds.send(dps);
}
catch(Exception e)
{
System.out.println("出错了。。。。。 亲");
}
}
}
}
|