"
import java.io.; import java.net.;
class Send implements Runnable { private DatagramSocket ds; public Send(DatagramSocket ds) { this.ds = ds; }
public void run()
{
try
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = bufr.readLine())!=null)
{
if("886".equals(line))
break;
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.105"),10002);
ds.send(dp);
}
}
catch(Exception e)
{
throw new RuntimeException("发送端失败");
}
}
}
class Rece implements Runnable { private DatagramSocket ds; public Rece(DatagramSocket ds) { this.ds = ds; }
public void run()
{
try
{
while(true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+data);
}
}
catch(Exception e)
{
throw new RuntimeException("接收端失败");
}
}
}
class ChartDemo { public static void main(String[] args)throws Exception { DatagramSocket sendSocket = new DatagramSocket(); DatagramSocket receSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}
在上面这段代码里,如果要实现两台电脑的交流,需要在什么样的网络环境下进行呢?
比如我将 DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.105"),10002);这行代码里的ip地址修改一下改成别的电脑的,在什么样的网络环境下可以实现呢?
"
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。