本帖最后由 glbai 于 2014-8-18 11:28 编辑
import java.net.*;
import java.io.*;
/*
需求:通过发送端键盘录入信息,在接收端显示接收消息
*/
class UdpChatSend
{
public static void main(String[] args) throws Exception
{
//System.out.println("Hello World!");
//通过键盘录入进行信息交互
DatagramSocket ds=new DatagramSocket();
BufferedReader bufR=new BufferedReader(new InputStreamReader(System.in));
//byte[] buf=new byte[1024];
String line=null;
while((line=bufR.readLine())!=null)
{
if("over".equals(line))
break;
//byte[] buf=new byte[1024];
byte[] buf=line.getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.158"),5001);
ds.send(dp);
System.out.println("192.168.1.158"+"::"+line);
}
bufR.close();
ds.close();
}
}
class UdpChatRecv
{
public static void main(String[] args) throws Exception
{
DatagramSocket ds=new DatagramSocket(5001);
byte[] buf=new byte[1024];
while(true)
{
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip=dp.getAddress().getHostAddress();
String str=new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+str);
}
//ds.close();
}
}
运行后,在发送端键盘输入无反应,应该是readLine阻塞问题 求大神帮忙解答一下 谢谢! |
|