📄 sender.java
字号:
package datagram003packet;
import javax.microedition.io.*;//use the datagramSocket
import java.io.*;//use the ByteArratOutputStream dATAOUTPUTSTREAM
public class Sender extends Thread implements Runnable {
private DatagramConnection dc;
private String mesg;
private String address;
public Sender(DatagramConnection dc)
{
this.dc=dc;
this.start();
}
//creat the function send()
public synchronized void send(String mesg,String address)
{
this.mesg=mesg;
this.address=address;
try
{
this.notify();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//creat the function stopSend()
public synchronized void stopSend()
{
this.mesg=null;
try
{
this.notify();
}
catch(Exception e)
{
e.printStackTrace();
}
}
//creat the function run()
public synchronized void run()//实现了对Run()的三种状态:阻塞,终止,激活三太
{
while(true)
{
System.out.println("Sender.run()");
if(this.mesg==null)
{
try
{
this.wait();//线程处与等待状态,
}
catch(Exception e)
{
e.printStackTrace();
}
}
if(this.mesg==null)
{
break;//线程处与终止状态
}
ByteArrayOutputStream bos=new ByteArrayOutputStream ();//线程激活
DataOutputStream dos=new DataOutputStream(bos);
try
{
dos.writeUTF(mesg);
dos.writeUTF("\r\n");
dos.flush();
byte[]buf=bos.toByteArray();
Datagram dg;
if(address==null)
{
dg=dc.newDatagram(buf,buf.length);
}
else
{
dg=dc.newDatagram(buf,buf.length,address);
}
dc.send(dg);
System.out.println("你所发送的字节长度为:"+dg.getData().length);
System.out.println("dg::"+dg);
mesg=null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -