private final void socketrun() {
   do {
     if (link.socketport != 0) {
       try {
         Socket socket =
             new Socket(InetAddress.getByName(getCodeBase().getHost()), link.socketport);
         socket.setSoTimeout(30000);
         socket.setTcpNoDelay(true);
         link.s = socket;
       } catch (Exception _ex) {
         link.s = null;
       }
       link.socketport = 0;
     }
     if (link.runme != null) {
       Thread thread = new Thread(link.runme);
       thread.setDaemon(true);
       thread.start();
       link.runme = null;
     }
     if (link.iplookup != null) {
       String s = "unknown";
       try {
         s = InetAddress.getByName(link.iplookup).getHostName();
       } catch (Exception _ex) {
       }
       link.host = s;
       link.iplookup = null;
     }
     try {
       Thread.sleep(100L);
     } catch (Exception _ex) {
     }
   } while (true);
 }
Example #2
1
  public static void main(String[] args) throws IOException, InterruptedException {
    boolean running = true;
    // udp protocol over a socket.
    DatagramSocket socket = new DatagramSocket();

    while (running) {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String line = br.readLine();
      String[] inputs = line.split(" ");

      if (inputs.length < 2) {
        System.out.println("Usage: username command id");
        socket.close();
        return;
      }

      byte[] byteArr = (inputs[0] + " " + inputs[1] + " " + inputs[2]).getBytes();

      // send request
      byte[] buf = new byte[256];
      InetAddress address = InetAddress.getByName("localhost");
      DatagramPacket packet = new DatagramPacket(byteArr, byteArr.length, address, 4445);
      socket.send(packet);

      // get response
      packet = new DatagramPacket(buf, buf.length);
      socket.receive(packet);

      // display response
      String received = new String(packet.getData(), 0, packet.getLength());
      System.out.println("From server: " + received);
    }
    //   socket.close();
  }
 public BroadcastClient(String ipAddress, int ipPort, String nicAddress, int nicPort)
     throws IOException {
   this.ipPort = ipPort; // Deprication
   this.nicPort = nicPort;
   this.type = Type.MULTICAST;
   this.direction = Direction.RECEIVE;
   try {
     this.nicAddress = InetAddress.getByName(nicAddress);
     this.ipAddress = InetAddress.getByName(ipAddress);
   } catch (UnknownHostException e) {
   }
   socket = new MulticastSocket(this.nicPort);
   socket.setInterface(this.nicAddress);
   socket.joinGroup(this.ipAddress);
 }
Example #4
0
  public static void main(String args[]) throws Exception {
    // Making a text file
    String filename =
        "C:\\Users\\S.S. Mehta\\Desktop\\Codes\\ComputerNetworks\\CN_project\\CN_project\\test3.txt";
    makeTextFile(filename);

    // Reading the file and puttin it in buffer
    BufferedReader in = new BufferedReader(new FileReader(filename));
    char[] c1 = new char[PACKET_SIZE];
    c1 = readData(in);
    displayPacket(c1);

    // Step3 - making a socket , makeing a packet with inet address and sending it
    byte[] buffer = new byte[PACKET_SIZE];
    DatagramSocket skt = new DatagramSocket(PORT_NUMBER);
    DatagramPacket request = new DatagramPacket(buffer, buffer.length);

    // stop till you receive
    wait(skt, request);
    System.out.println("On server side \nrequest received from Slient");
    // making a packet with an inet address -
    InetAddress host = InetAddress.getByName("localhost");

    DatagramPacket reply = makePacket(c1, host);

    // Sending reply packet
    System.out.println("Sending reply packet to client");
    Thread.sleep(5000);
    skt.send(reply);

    // closing the socket
    skt.close();
  }
 /** @param args the command line arguments */
 public static void main(String[] args) throws Exception {
   try {
     conf = new JsonFile("config.json").read();
     address = conf.getJson().get("bind_IP").toString();
     port = Integer.parseInt(conf.getJson().get("port").toString());
     collection = new CollectThread(conf);
     collection.start();
     s = new ServerSocket(port, 50, InetAddress.getByName(address));
     System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
     System.out.print("listening on: " + address + ":" + port + "\n");
   } catch (Exception e) {
     System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
     System.out.print("error: " + e);
   }
   while (true) {
     try {
       sock = s.accept();
       System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
       System.out.print("connection from " + sock.getInetAddress() + ":");
       System.out.print(sock.getPort() + "\n");
       server = new ConsoleThread(conf, sock);
       server.start();
     } catch (Exception e) {
       System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
       System.out.print("error: " + e);
       continue;
     }
   }
 }
Example #6
0
  public static void main(String[] args) {
    int port = 5555;

    DatagramSocket socket;
    socket = null;
    try {
      socket = new DatagramSocket(port);
      socket.setBroadcast(true);
      socket.connect(InetAddress.getByName("255.255.255.255"), 5555);
    } catch (Exception e) {
      System.err.println("Connection failed. " + e.getMessage());
    }

    while (true) {
      String message = "hey";
      byte[] buf = message.getBytes();

      DatagramPacket packet = new DatagramPacket(buf, buf.length);
      try {
        socket.send(packet);
      } catch (Exception e) {
        System.err.println("Sending failed. " + e.getMessage());
      }
    }
  }
Example #7
0
  protected InetSocketAddress readAddress() throws IOException {
    // Address
    int addressType = input.read();
    InetAddress address;
    switch (addressType) {
      case 1: // IPv4
        byte[] ip4 = new byte[4];
        readFully(ip4);
        address = Inet4Address.getByAddress(ip4);
        break;

      case 3: // Domain name
        int size = input.read();
        byte[] domain = new byte[size];
        readFully(domain);
        address = InetAddress.getByName(new String(domain, "US-ASCII"));
        break;

      case 4: // IPv6
        byte[] ip6 = new byte[16];
        readFully(ip6);
        address = Inet6Address.getByAddress(ip6);
        break;

      default:
        throw new SOCKS5Exception(
            "Unexpected address type in SOCKS server response: " + addressType);
    }

    // Port
    int port = (input.read() << 8) | input.read();

    return new InetSocketAddress(address, port);
  }
 public MulticastServerThread(String username, String multicastIPAddress, int multicastPort)
     throws UnknownHostException {
   super("MulticastServerThread");
   group = InetAddress.getByName(multicastIPAddress);
   this.username = username;
   this.multicastPort = multicastPort;
 }
  /** 启动初始化,他确定网络中有多少个其它UDPBase和相关的信息 */
  public void initNet() throws UDPBaseException {
    try {
      mainThread = new SoleThread(this);

      localIP = InetAddress.getLocalHost().getHostAddress();
      int i = localIP.lastIndexOf('.');
      BROADCAST_ADDR = localIP.substring(0, i) + ".255";
      // System.out.println ("lip=="+localIP) ;
      // sendSocket = new DatagramSocket () ;
      // recvSocket = new MulticastSocket (RECV_PORT) ;
      recvSocket = new DatagramSocket(RECV_PORT);
      sendSocket = recvSocket;
      // recvAckSocket = new MulticastSocket (RECV_ACK_PORT) ;
      group = InetAddress.getByName(BROADCAST_ADDR);
      // recvSocket.joinGroup (group) ;
      // recvAckSocket.joinGroup (group) ;

      procMsgThd = new ProcMsgThd();
      procMsgThd.start();
      //
      mainThread.start();
    } catch (Exception e) {
      e.printStackTrace();
      throw new UDPBaseException("UDPBase init() error=\n" + e.toString());
    }
  }
Example #10
0
  /**
   * Konstruktor
   *
   * @param configFile Jmeno konfiguracniho souboru
   */
  public Server(String configFile) {
    setServerConfig(new ServerConfig(configFile));

    setPort(getServerConfig().getPort());
    try {
      setBindAddress(InetAddress.getByName(getServerConfig().getBindAddress()));
    } catch (UnknownHostException e) {
      System.err.println("Bind adresa neni platna!");
      System.exit(-1);
    }

    try {
      setServerSocket(new ServerSocket(getPort(), 0, getBindAddress()));
    } catch (IOException e) {
      System.err.println("Chyba startu ServerSocketu");
      System.exit(-1);
    }

    System.out.println("Server spusten");

    clients = new Hashtable<String, ServerThread>();
    boolean running = true;
    while (running) {
      try {
        accept();
      } catch (IOException e) {
        System.err.println("Chyba acceptu");
        running = false;
      }
    }
  }
 Target(String host) {
   try {
     address = new InetSocketAddress(InetAddress.getByName(host), 80);
   } catch (IOException x) {
     failure = x;
   }
 }
 public static void main(String args[]) {
   DatagramSocket aSocket = null;
   try {
     aSocket = new DatagramSocket();
     String stringMsg = "0";
     String prevReply = "0";
     InetAddress aHost =
         InetAddress.getByName("localhost"); // recieve a message from the same computer
     int serverPort = 6789; // agreed port
     while (true) {
       stringMsg = "" + (Integer.parseInt(stringMsg) + 1);
       byte[] message = stringMsg.getBytes();
       DatagramPacket request = new DatagramPacket(message, message.length, aHost, serverPort);
       System.out.printf("Producer: Sending: %s\n", stringMsg);
       aSocket.send(request); // send a message
       byte[] buffer = new byte[1000];
       DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
       aSocket.receive(reply); // wait for a reply
       try {
         Thread.sleep(2000); // have a small waiting period
       } catch (InterruptedException e) {
       }
     }
   } catch (SocketException e) {
     System.out.println("Socket: " + e.getMessage());
   } catch (IOException e) {
     System.out.println("IO: " + e.getMessage());
   } finally {
     if (aSocket != null) aSocket.close();
   }
 }
Example #13
0
  public static void main(String args[]) throws Exception {

    String serverHostname = args[0];
    int portNumber = Integer.parseInt(args[1]);

    try {
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

      DatagramSocket clientSocket = new DatagramSocket();

      InetAddress IPAddress = InetAddress.getByName(serverHostname);
      System.out.println("Attempting to connect to " + IPAddress + ") via UDP port " + portNumber);
      System.out.println("Enter \"Quit\" to exit program");

      while (true) {
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        System.out.print("Enter Message: ");
        String sentence = inFromUser.readLine();

        if (sentence.equals("Quit")) break;

        sendData = sentence.getBytes();

        System.out.println("Sending data to " + sendData.length + " bytes to server.");
        DatagramPacket sendPacket =
            new DatagramPacket(sendData, sendData.length, IPAddress, portNumber);

        clientSocket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

        System.out.println("Waiting for return packet");
        clientSocket.setSoTimeout(10000);

        try {
          clientSocket.receive(receivePacket);
          String modifiedSentence = new String(receivePacket.getData());

          InetAddress returnIPAddress = receivePacket.getAddress();

          int port = receivePacket.getPort();

          System.out.println("From server at: " + returnIPAddress + ":" + port);
          System.out.println("Message: " + modifiedSentence);
        } catch (SocketTimeoutException ste) {
          System.out.println("Timeout Occurred: Packet assumed lost");
        }
        System.out.print("\n");
      }

      clientSocket.close();
    } catch (UnknownHostException ex) {
      System.err.println(ex);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Example #14
0
 // Check for an IP, since this seems to be safer to return then a plain name
 private String getIpIfPossible(String pHost) {
   try {
     InetAddress address = InetAddress.getByName(pHost);
     return address.getHostAddress();
   } catch (UnknownHostException e) {
     return pHost;
   }
 }
Example #15
0
 public Server(int port, int backlog, String ip) {
   try {
     server = new ServerSocket(port, backlog, InetAddress.getByName(ip));
   } catch (IOException e) {
     System.out.println("Can't initialize server: " + e.getMessage());
     // TODO: exit main thread
   }
 }
Example #16
0
 public InetAddress address(String address) {
   try {
     return InetAddress.getByName(address);
   } catch (UnknownHostException e) {
     System.out.println("Unknown host: " + address);
     return null;
   }
 }
Example #17
0
  public static void main(String args[]) throws Exception {

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

    DatagramSocket clientSocket = new DatagramSocket();

    InetAddress IPAddress = InetAddress.getByName("192.168.1.16");

    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];

    String sentence = new String("HELLO");
    sendData = sentence.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
    clientSocket.send(sendPacket);
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
    if (sentence.equals("##100##")) {
      System.out.println(sentence + ": Waiting for Red.");
    }
    while (!sentence.equals("##200##")) {
      try {
        receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
      } catch (Exception e) {

      }
    }
    if (sentence.equals("##200##")) {
      System.out.println(sentence + ": Red and Blue are connected");
    }

    while (true) {
      receiveData = new byte[1024];
      receivePacket = new DatagramPacket(receiveData, receiveData.length);

      clientSocket.receive(receivePacket);

      sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

      if (sentence.equals("##300##")) {
        break;
      }

      System.out.println("RED: " + sentence);

      sentence = inFromUser.readLine();
      sendData = sentence.getBytes();
      sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

      clientSocket.send(sendPacket);
    }
    System.out.println(sentence + ": Disconnected.");
    clientSocket.close();
  }
  /**
   * Sends a leave message to the multicast group and leaves it. The <CODE>DiscoveryResponder</CODE>
   * leaves its multicast group. This method has no effect if the <CODE>DiscoveryResponder</CODE> is
   * <CODE>OFFLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>.
   */
  public void stop() {
    if (state == ONLINE) {
      changeState(STOPPING);
      // ------------------------
      // Stop corresponding thread
      // ------------------------

      responder.stopRequested = true;

      synchronized (responder.interrupted) {
        if (!responder.interrupted.booleanValue()) {
          responderThread.interrupt();
        }
      }

      // Fix for cases when the interrupt does not work (Windows NT)
      try {
        MulticastSocket ms = new MulticastSocket(multicastPort);

        // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001
        if (usrInet != null) {
          ms.setInterface(usrInet);

          if (logger.finerOn()) {
            logger.finer("stop ", "use the interface " + usrInet);
          }
        }
        // end of NPCTE fix for bugId 4499338

        InetAddress group = InetAddress.getByName(multicastGroup);
        ms.joinGroup(group);
        ms.send(new DatagramPacket(new byte[1], 1, group, multicastPort));
        ms.leaveGroup(group);
      } catch (Exception e) {
        if (logger.finerOn()) {
          logger.finer(
              "stop ",
              "Unexpected exception occurred trying to send empty message " + e.getMessage());
        }
      }

      // ------------------------
      // free 'remained' allocated resource
      // ------------------------
      responder = null;
      System.runFinalization();

      // ----------------
      // Update state
      // ----------------
      // changeState(OFFLINE) ;
    } else {
      if (logger.finerOn()) {
        logger.finer("stop ", "Responder is not ONLINE");
      }
    }
  }
 public static InetAddress arrayToInetAddress(byte[] addr, int offset) {
   int[] i = byteToIntArray(addr, offset, 4);
   String s = i[0] + "." + i[1] + "." + i[2] + "." + i[3];
   try {
     return InetAddress.getByName(s);
   } catch (UnknownHostException e) {
     throw new RuntimeException("unknown host: " + s);
   }
 }
Example #20
0
 public static void main(String args[]) throws UnknownHostException {
   ChatClient client = null;
   InetAddress address;
   if (args.length != 2) System.out.println("Usage: java ChatClient host port");
   else {
     address = InetAddress.getByName(args[0]);
     client = new ChatClient(address, Integer.parseInt(args[1]));
   }
 }
Example #21
0
 public static String inaddrString(String s) {
   InetAddress address;
   try {
     address = InetAddress.getByName(s);
   } catch (UnknownHostException e) {
     return null;
   }
   return inaddrString(address);
 }
Example #22
0
 public byte[] getRAddr() {
   try {
     InetAddress addr = InetAddress.getByName(host);
     return addr.getAddress();
   } catch (UnknownHostException e) {
     System.err.println("NCCPConnection::getRAddr Don't know about host: ");
     return null;
   }
 }
  public static void start(int serverPort) {
    String address =
        "127.0.0.1"; // это IP-адрес компьютера, где исполняется наша серверная программа.
    // Здесь указан адрес того самого компьютера где будет исполняться и клиент.
    try {
      InetAddress ipAddress =
          InetAddress.getByName(
              address); // создаем объект который отображает вышеописанный IP-адрес.
      System.out.println(
          "Any of you heard of a socket with IP address "
              + address
              + " and port "
              + serverPort
              + "?");
      Socket socket =
          new Socket(ipAddress, serverPort); // создаем сокет используя IP-адрес и порт сервера.
      System.out.println("Yes! I just got hold of the program.");

      // Берем входной и выходной потоки сокета, теперь можем получать и отсылать данные клиентом.
      InputStream sin = socket.getInputStream();
      OutputStream sout = socket.getOutputStream();

      // Конвертируем потоки в другой тип, чтоб легче обрабатывать текстовые сообщения.
      DataInputStream in = new DataInputStream(sin);
      DataOutputStream out = new DataOutputStream(sout);

      // Создаем поток для чтения с клавиатуры.
      BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
      String line = null;
      System.out.println(
          "Type in something and press enter. Will send it to the server and tell ya what it thinks.");
      System.out.println();

      while (true) {
        line = keyboard.readLine(); // ждем пока пользователь введет что-то и нажмет кнопку Enter.
        if (line == null) {
          continue;
        }
        System.out.println("Sending this line to the server...");
        out.writeUTF(line); // отсылаем введенную строку текста серверу.
        out.flush(); // заставляем поток закончить передачу данных.
        boolean isTransactionSucceed = in.readBoolean(); // ждем пока сервер отошлет ответ.
        if (isTransactionSucceed) {
          System.out.println("Success!");
        } else {
          System.out.println("Failed");
        }
        System.out.println();
      }
    } catch (SocketException x) {
      System.out.println("Server doesn't response anymore");
      System.out.println();
    } catch (Exception x) {
      x.printStackTrace();
    }
  }
Example #24
0
 /**
  * Creates a SimpleResolver that will query the specified host
  *
  * @exception UnknownHostException Failure occurred while finding the host
  */
 public SimpleResolver(String hostname) throws UnknownHostException {
   if (hostname == null) {
     hostname = ResolverConfig.getCurrentConfig().server();
     if (hostname == null) hostname = defaultResolver;
   }
   InetAddress addr;
   if (hostname.equals("0")) addr = InetAddress.getLocalHost();
   else addr = InetAddress.getByName(hostname);
   address = new InetSocketAddress(addr, DEFAULT_PORT);
 }
  ProcessB() {
    this.setPort(5000);
    this.setHost("localhost");
    try {
      this.setAddress(InetAddress.getByName(getHost()));

    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }
Example #26
0
  /** Generic constructor for the name service interface */
  public LeetActive(String svc_host, int svc_port, int portNum) {

    try {
      nameServer = new DatagramSocket();
      nameServer.setSoTimeout(3000);
      nameServer.connect(InetAddress.getByName(svc_host), svc_port);
    } catch (Exception e) {
      System.err.println("LA " + e);
    }
    this.portNum = portNum;
    hostList = new ArrayList();
  }
Example #27
0
  public void Connect() throws IOException {
    try {
      InetAddress addr = InetAddress.getByName(server);
      Socket socket = new Socket(addr, port);

      in = new InputStreamReader(socket.getInputStream());
      out = new OutputStreamWriter(socket.getOutputStream());

      char c[] = new char[LINE_LENGTH];

      boolean authed = false;

      while (true) {
        if (in.read(c) > 0) {
          String msg = new String(c).trim();

          if (!authed) {
            if (msg.endsWith("No Ident response")) {

              System.out.println("...sending identity...");
              out.write(String.format("NICK %s\r\n", nickname));
              out.write(String.format("USER %s %s %s :s\r\n", nickname, host, server, realname));
              out.flush();

              authed = true;

              for (IRCAuthListener a : authListeners) {
                a.afterAuthentication(this);
              }
            }
          }

          if (msg.startsWith("PING")) {
            System.out.println("Sending pong...");
            out.write("PONG\r\n");
            out.flush();
          }

          for (IRCRawDataListener d : rawDataListeners) {
            d.processRawData(this, msg);
          }

          c = new char[LINE_LENGTH];
        } else {
          System.out.println("Oops, if you see this we just got kicked or connection timed out...");
          break;
        }
      }
    } catch (IOException ioe) {
      throw (ioe);
    }
  }
Example #28
0
 public static void main(String[] args) {
   try (DatagramSocket socket = new DatagramSocket(0)) {
     socket.setSoTimeout(10000);
     InetAddress host = InetAddress.getByName(HOSTNAME);
     DatagramPacket request = new DatagramPacket(new byte[1], 1, host, PORT);
     DatagramPacket response = new DatagramPacket(new byte[1024], 1024);
     socket.send(request);
     socket.receive(response);
     String result = new String(response.getData(), 0, response.getLength(), "US-ASCII");
     System.out.println(result);
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
Example #29
0
 void run() {
   try {
     // 1. creating a socket to connect to the server
     requestSocket = new DatagramSocket();
     serverAddr = InetAddress.getByName(serverIpAddr);
     registerWithServer();
     receiveInitialBoardStateAndInitializeBoard();
     listenToServer();
   } catch (UnknownHostException unknownHost) {
     System.err.println("You are trying to connect to an unknown host!");
   } catch (IOException ioException) {
     ioException.printStackTrace();
   } finally {
     requestSocket.close();
     System.exit(0);
   }
 }
Example #30
-1
 public UDPEcho(String host, int port) throws IOException, UnknownHostException {
   this.hostIP = InetAddress.getByName(host);
   this.port = port;
   sock = new DatagramSocket();
   System.out.println("UDP: " + sock.getLocalAddress() + ":" + sock.getLocalPort());
   // sock.connect(hostIP,port);
 }