我已经使我的pc服务器和客户端,并能够传递消息从一个cmd窗口到另一个。但是,当我没有连接到互联网时,我仍然能够做到这一点。,这怎么可能。?,这是我的代码。
import java.net.*;
class tester {
static int pos=0;
static byte buffer[]=new byte[100];
static void Client() throws Exception {
InetAddress address=InetAddress.getLocalHost();
DatagramSocket ds=new DatagramSocket();
while(pos<buffer.length) {
int c=System.in.read();
buffer[pos++]=(byte)c;
if((char)c=='\n')
break;
}
ds.send(new DatagramPacket(buffer,pos,address,3000));
}
static void Server() throws Exception {
InetAddress address=InetAddress.getLocalHost();
DatagramSocket ds=new DatagramSocket(3000,address);
DatagramPacket dp=new DatagramPacket(buffer,buffer.length);
ds.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());
System.out.print(s);
}
public static void main(String args[])throws Exception {
if(args.length==1) {
Client(); }
else {
Server();
}
}
}发布于 2011-03-26 06:13:42
你不明白第一个问题的答案吗?
您的计算机已启用网络。您的服务器正在监听127.0.0.1,而您的客户端正在发送到127.0.0.1。
如果未分配可路由IP地址,InetAddress.getLocalHost()将返回回送地址。
https://stackoverflow.com/questions/5440655
复制相似问题