本帖最后由 ╰青青子佩ˊゝ 于 2014-3-29 09:13 编辑
你同时开启了发送端和接收端两个线程,输入结束标记"baibai"后,只是结束了发送端线程,接收端线程还在运行状态,在等接收数据,程序还没结束。当然,发送端都关闭了,肯定就不能在控制台输入并发送数据。下面代码改了两个地方,就可以做到你要的效果了。- import java.io.*;
- import java.net.*;
- class Testg
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket dt=new DatagramSocket();
- DatagramSocket dgt=new DatagramSocket(10002);
- new Thread(new Send(dt)).start();
- new Thread(new Receive(dgt)).start();
- }
- }
- class Send implements Runnable
- {
- private DatagramSocket dt;
- public Send(DatagramSocket dt){
- this.dt=dt;
- }
- public void run()
- {
- try
- {
- BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- while ((line=bfr.readLine())!=null)
- {
- byte[] by=line.getBytes();
- DatagramPacket dst=new DatagramPacket(by,by.length,InetAddress.getByName("192.168.1.100"),10002);
- dt.send(dst);
- //1.这个if语句从上面挪到这个位置
- if (line.equals("baibai"))
- {
- break;
- }
- }
- dt.close();
- //bfr.close();
- }
- catch(Exception e)
- {
- throw new RuntimeException("fasongshibai");
- }
- }
- }
- class Receive implements Runnable
- {
- private DatagramSocket dt;
- public Receive(DatagramSocket dt)
- {
- this.dt=dt;
- }
- public void run()
- {
- try
- {
- while(true)
- {
- byte [] by=new byte[1024];
- DatagramPacket dpt=new DatagramPacket(by,by.length);
- dt.receive(dpt);
- System.out.println(new String(dpt.getData(),0,dpt.getLength()));
- //2.这里加一个if语句判断,是的接收端线程也能结束
- if(new String(dpt.getData(),0,dpt.getLength()).equals("baibai"))
- break;
- }
- //dt.close();
- }
- catch(Exception e)
- {
- throw new RuntimeException("jieshoushibai");
- }
- }
- }
复制代码
|