开发者

How could the message be exchanged? _networking_

I have made my pc both server and client and am able 开发者_如何学Pythonto pass messages from one cmd window to another. But i am still able to do so when i am not connected to internet.How is that possible.?This is My code.

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();
    }
 }
}


Did you not understand the answer to your first question?

Your computer has networking enabled. Your server is listening on 127.0.0.1 and your client is sending to 127.0.0.1.

InetAddress.getLocalHost() returns the loopback address if you have not been assigned a routeable IP address.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜