// 获得IP地址 public static String getIpAddr(HttpServletRequest request) { String ipAddress = null; ipAddress = request.getHeader("x-forwarded-for"); if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getHeader("WL-Proxy-Client-IP"); } if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { ipAddress = request.getRemoteAddr(); if (ipAddress.equals("127.0.0.1")) { // 根据网卡取本机配置的IP InetAddress inet = null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ipAddress = inet.getHostAddress(); } } // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() // = 15 if (ipAddress.indexOf(",") > 0) { ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); } } return ipAddress; }
/** * Creates a new, empty SessionDescription. The session is set as follows: * * <p>v=0 * * <p>o=this.createOrigin ("user", InetAddress.getLocalHost().toString()); * * <p>s=- * * <p>t=0 0 * * @throws SdpException SdpException, - if there is a problem constructing the SessionDescription. * @return a new, empty SessionDescription. */ public SessionDescription createSessionDescription() throws SdpException { SessionDescriptionImpl sessionDescriptionImpl = new SessionDescriptionImpl(); ProtoVersionField ProtoVersionField = new ProtoVersionField(); ProtoVersionField.setVersion(0); sessionDescriptionImpl.setVersion(ProtoVersionField); OriginField originImpl = null; try { originImpl = (OriginField) this.createOrigin("user", InetAddress.getLocalHost().getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } sessionDescriptionImpl.setOrigin(originImpl); SessionNameField sessionNameImpl = new SessionNameField(); sessionNameImpl.setValue("-"); sessionDescriptionImpl.setSessionName(sessionNameImpl); TimeDescriptionImpl timeDescriptionImpl = new TimeDescriptionImpl(); TimeField timeImpl = new TimeField(); timeImpl.setZero(); timeDescriptionImpl.setTime(timeImpl); Vector times = new Vector(); times.addElement(timeDescriptionImpl); sessionDescriptionImpl.setTimeDescriptions(times); sessionDescriptionsList.addElement(sessionDescriptionImpl); return sessionDescriptionImpl; }
private boolean connectSPPMon() { if (state == ConnectionEvent.CONNECTION_PENDING) { ExpCoordinator.print( new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0); while (state == ConnectionEvent.CONNECTION_PENDING) { try { Thread.sleep(500); } catch (java.lang.InterruptedException e) { } } return (isConnected()); } state = ConnectionEvent.CONNECTION_PENDING; if (nonProxy != null) { try { nonProxy.connect(); } catch (UnknownHostException e) { boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage()); return rtn; } catch (SocketTimeoutException e) { boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage()); return rtn; } catch (IOException e) { boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage()); return rtn; } } return (isConnected()); }
/** * 获取本机ip * * @return */ public static String GetIpAdd() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { // TODO 自动生成 catch 块 return e.getMessage(); // e.printStackTrace(); } }
public Process(String name, int pid, int n) { this.name = name; this.port = Utils.REGISTRAR_PORT + pid; this.host = "UNKNOWN"; try { this.host = (InetAddress.getLocalHost()).getHostName(); } catch (UnknownHostException e) { String msg = String.format("Error: getHostName() failed at %s.", this.getInfo()); System.err.println(msg); System.err.println(e.getMessage()); System.exit(1); } this.pid = pid; this.n = n; random = new Random(); /* Accepts connections from one of Registrar's worker threads */ new Thread(new Listener(this)).start(); /* Connect to registrar */ socket = connect(); init(); Utils.out(pid, "Connected."); }
public Server() { try { ServerSocket ss = new ServerSocket(SERVER_PORT); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream out = s.getOutputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String sss = br.readLine(); System.out.println(sss); PrintWriter pw = new PrintWriter(out); pw.print("hello,我是服务器。"); pw.close(); br.close(); isr.close(); out.close(); is.close(); s.close(); ss.close(); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (IOException oe) { oe.printStackTrace(); } }
public boolean connectToServer(String ip, String userName) { try { socket = new Socket(ip, 45322); lnOut("Connected to server!"); ; streamFromServer = new DataInputStream(socket.getInputStream()); streamToServer = new DataOutputStream(socket.getOutputStream()); // With the connection established, create the server connection module. serverCon = new ServerConnection(this, streamToServer); // next start a thread that listens to incoming // messages from the game server via TCP. listener = new TCPListenerThread(this, client, streamFromServer); // finally send the requested user name to the server. streamToServer.write(userName.getBytes()); return true; } catch (UnknownHostException e) { System.out.println("Don't know about host: " + ip); System.out.println(e.getMessage()); return false; } catch (IOException e) { System.out.println("Couldn't get I/O for the connection to: " + ip); System.out.println(e.getMessage()); return false; } catch (Exception e) { System.out.println(e.getMessage()); return false; } }
/** @param args the command line arguments */ public static void main(String[] args) { try { int randomNum = (int) ((Math.random() * 100) + 1); Socket server = new Socket("127.0.0.1", 8888); BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter output = new PrintWriter(server.getOutputStream(), true); String leggi; int total = 0; output.println(randomNum); while ((leggi = input.readLine()) != null) { System.out.println("Valore letto: " + leggi); total += Integer.parseInt(leggi); } System.out.println("Somma dei valori ricevuti dal Server: " + total); if (total % 2 == 0) { System.out.println("PARI"); } else { System.out.println("DISPARI"); } } catch (UnknownHostException ex) { System.out.println("Errore indirizzo sconosciuto:" + ex.getMessage()); } catch (IOException ex) { System.out.println(ex); } }
public static String ip() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); return null; } }
/** * Gets the next token from a tokenizer and converts it to an IP Address. * * @param family The address family. * @return The next token in the stream, as an InetAddress * @throws TextParseException The input was invalid or not a valid address. * @throws IOException An I/O error occurred. * @see Address */ public InetAddress getAddress(int family) throws IOException { String next = _getIdentifier("an address"); try { return Address.getByAddress(next, family); } catch (UnknownHostException e) { throw exception(e.getMessage()); } }
ProcessB() { this.setPort(5000); this.setHost("localhost"); try { this.setAddress(InetAddress.getByName(getHost())); } catch (UnknownHostException e) { e.printStackTrace(); } }
@Override public void run() { try { Thread.sleep(3000); String uberdustServerDnsName = config.getString("uberdustcoapserver.dnsName"); if (uberdustServerDnsName == null) { throw new Exception("Property uberdustcoapserver.dnsName not set."); } int uberdustServerPort = config.getInt("uberdustcoapserver.port", 0); if (uberdustServerPort == 0) { throw new Exception("Property uberdustcoapserver.port not set."); } InetSocketAddress uberdustServerSocketAddress = new InetSocketAddress(InetAddress.getByName(uberdustServerDnsName), uberdustServerPort); String baseURI = config.getString("baseURIHost", "localhost"); CoapRequest fakeRequest = new CoapRequest( MsgType.NON, Code.POST, new URI("coap://" + baseURI + ":5683/here_i_am")); CoapNodeRegistrationServer registrationServer = CoapNodeRegistrationServer.getInstance(); if (registrationServer == null) { log.error("NULL!"); } registrationServer.receiveCoapRequest(fakeRequest, uberdustServerSocketAddress); } catch (InterruptedException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (URISyntaxException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InvalidMessageException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InvalidOptionException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (ToManyOptionsException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
private Descrittore contatta_server(String nome) { // variabili per l'RMI RMIServerInt serv = null; // server Descrittore descr_rit = null; // descrittore ritornato if (nome == null) { System.out.println("## contatta_server di Download ha ricevuto parametro null ! "); return null; } System.out.println("@ provo a contattare il server RMI "); // ################ RMI ################ if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } Object o = null; try { // o = Naming.lookup("rmi://192.168.0.10:1099/srmi"); Registry registry = LocateRegistry.getRegistry(server.getHostAddress()); o = registry.lookup("srmi"); } catch (RemoteException e) { System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome); e.printStackTrace(); } catch (NotBoundException e) { System.out.println("## Problemi nell'RMI di Download - contatta_server di " + nome); e.printStackTrace(); } if (o == null) { System.out.println( "## l'RMI di Download - contatta_server di " + nome + " ha ritornato l'oggetto o null"); return null; } serv = (RMIServerInt) o; try { descr_rit = serv.lookup(nome, InetAddress.getLocalHost()); } catch (RemoteException e) { e.printStackTrace(); System.out.println("## Problemi con Lookup di " + nome); return null; } catch (UnknownHostException e) { e.printStackTrace(); System.out.println("## Problemi con Lookup di " + nome); return null; } return descr_rit; }
public void connect() { try { s = new Socket("127.0.0.1", 8888); dos = new DataOutputStream(s.getOutputStream()); System.out.println("connected!"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String[] args) { Socket socket = null; PrintWriter out = null; BufferedReader in = null; BufferedReader userInputStream = null; String IP = "127.0.0.1"; final int PORT_NUM = 4444; try { socket = new Socket(IP, PORT_NUM); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host:" + IP + " at port: " + PORT_NUM); e.printStackTrace(); System.exit(0); } catch (IOException e) { System.out.println("Cannot connect to server..."); e.printStackTrace(); System.exit(0); } String userInput, fromServer; try { userInputStream = new BufferedReader(new InputStreamReader(System.in)); while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals(":q")) break; userInput = userInputStream.readLine(); Calendar cal = Calendar.getInstance(); cal.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); if (userInput != null) { out.println(userInput + " (sent at " + (sdf.format(cal.getTime())) + ")"); } } } catch (IOException e) { System.out.println("Could not access data from client printstream..."); e.printStackTrace(); System.exit(0); } try { out.close(); in.close(); userInputStream.close(); socket.close(); System.out.println("I love you, bye."); System.out.println("Terminating client..."); } catch (IOException e) { System.out.println("Socket and stream closing error..."); e.printStackTrace(); System.exit(0); } }
String getLocalIPAddr() { if (localAddr == null) { try { IPAddr localHost = IPAddr.getLocalHost(); localAddr = localHost.getHostAddress(); } catch (UnknownHostException e) { // shouldn't happen log.error("LockssServlet: getLocalHost: " + e.toString()); return "???"; } } return localAddr; }
public void Connect() { try { System.out.println("ok"); socket99 = new Socket(serverIP, 9999); socket66 = new Socket(serverIP, 6666); socket88 = new Socket(serverIP, 8888); isConnected = true; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public ChatClient(InetAddress iAddress, int serverPort) { System.out.println("Establishing connection. Please wait ..."); try { socket = new Socket(iAddress, serverPort); cryptor = new EDCrypt(); System.out.println("Connected: " + socket); start(); } catch (UnknownHostException uhe) { System.out.println("Host unknown: " + uhe.getMessage()); } catch (IOException ioe) { System.out.println("Unexpected exception: " + ioe.getMessage()); } }
private boolean establecer() { try { Mensaje msg = new MensajeSistema(); this.conexion = new Socket(msg.HOST_SERVER, msg.PUERTO); // FIXME correcto tratamiento del error /*if (!this.conexion) return false;*/ } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return true; }
/** * Returns the address of the local host. This is achieved by retrieving the name of the host from * the system, then resolving that name into an <code>InetAddress</code>. * * <p>Note: The resolved address may be cached for a short period of time. * * <p>If there is a security manager, its <code>checkConnect</code> method is called with the * local host name and <code>-1</code> as its arguments to see if the operation is allowed. If the * operation is not allowed, an InetAddress representing the loopback address is returned. * * @return the address of the local host. * @exception UnknownHostException if the local host name could not be resolved into an address. * @see SecurityManager#checkConnect * @see java.net.InetAddress#getByName(java.lang.String) */ public static InetAddress getLocalHost() throws UnknownHostException { SecurityManager security = System.getSecurityManager(); try { String local = impl.getLocalHostName(); if (security != null) { security.checkConnect(local, -1); } if (local.equals("localhost")) { return impl.loopbackAddress(); } InetAddress ret = null; synchronized (cacheLock) { long now = System.currentTimeMillis(); if (cachedLocalHost != null) { if ((now - cacheTime) < maxCacheTime) // Less than 5s old? ret = cachedLocalHost; else cachedLocalHost = null; } // we are calling getAddressFromNameService directly // to avoid getting localHost from cache if (ret == null) { InetAddress[] localAddrs; try { localAddrs = (InetAddress[]) InetAddress.getAddressFromNameService(local, null); } catch (UnknownHostException uhe) { throw new UnknownHostException(local + ": " + uhe.getMessage()); } cachedLocalHost = localAddrs[0]; cacheTime = now; ret = localAddrs[0]; } } return ret; } catch (java.lang.SecurityException e) { return impl.loopbackAddress(); } }
public void activateOptions() { InetAddress addr = null; try { Class c = Class.forName(decoder); Object o = c.newInstance(); if (o instanceof Decoder) { this.decoderImpl = (Decoder) o; } } catch (ClassNotFoundException cnfe) { getLogger().warn("Unable to find decoder", cnfe); } catch (IllegalAccessException iae) { getLogger().warn("Could not construct decoder", iae); } catch (InstantiationException ie) { getLogger().warn("Could not construct decoder", ie); } try { addr = InetAddress.getByName(address); } catch (UnknownHostException uhe) { uhe.printStackTrace(); } try { active = true; socket = new MulticastSocket(port); socket.joinGroup(addr); receiverThread = new MulticastReceiverThread(); receiverThread.start(); handlerThread = new MulticastHandlerThread(); handlerThread.start(); if (advertiseViaMulticastDNS) { zeroConf = new ZeroConfSupport(ZONE, port, getName()); zeroConf.advertise(); } } catch (IOException ioe) { ioe.printStackTrace(); } }
/** @return true if the request was served. */ private boolean proxyRemotePath( HttpServletRequest req, HttpServletResponse resp, URI remoteURI, boolean failEarlyOn404) throws IOException, ServletException, UnknownHostException { try { return proxyRemoteUrl(req, resp, new URL(remoteURI.toString()), failEarlyOn404); } catch (MalformedURLException e) { String message = NLS.bind("Malformed remote URL: {0}", remoteURI.toString()); handleException( resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, message, e)); } catch (UnknownHostException e) { String message = NLS.bind("Unknown host {0}", e.getMessage()); handleException( resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, message, e)); } catch (Exception e) { String message = NLS.bind("An error occurred while retrieving {0}", remoteURI.toString()); handleException( resp, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message, e)); } return true; }
public void update(EventBean[] newData, EventBean[] oldData) { System.out.println( "Transaction Id=" + newData[0].get("tid") + ": Latency Between Order Creation and Purchase Order=" + newData[0].get("LatencyAB") + " And Latency between Purchase Order and Shipping=" + newData[0].get("LatencyBC")); String ip = "172.17.76.74"; try { System.out.println("1--->Sending data..."); System.out.println(InetAddress.getByName(ip)); // UdpListener.sendDataOverUdp("TXNCEP.Order.LatencyAB", // newData[0].get("LatencyAB").toString(),InetAddress.getByName(ip),2003); UdpListener.sendDataOverUdp( /*"carbon.txncep.order.latencyab"*/ "carbon.installation.TXNCEP", newData[0].get("LatencyAB").toString(), InetAddress.getByName(ip), 2003); System.out.println("Sending data..."); } catch (SocketException e) { System.out.println("socket error - Socket Exception" + e.getMessage()); System.out.println(); } catch (UnknownHostException e) { System.out.println("socket error - UnknownHost" + e.getMessage()); } catch (PropertyAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** Creates new form Login */ public Login() { initComponents(); setTitle("Zlatna ribica"); /* napravit konekciju sa serverom */ String servername = "0.0.0.0"; /* pretpostavljen localhost */ int port = 1000; /* pretpostavljeno da server slusa na portu 23456 */ try { socket = new Socket(servername, port); streamOut = new DataOutputStream(socket.getOutputStream()); streamIn = new DataInputStream(socket.getInputStream()); } catch (UnknownHostException uhe) { System.err.println("Host unknown " + uhe.getMessage()); System.exit(0); } catch (IOException ioe) { System.err.println("Unexpected exception; " + ioe.getMessage()); System.exit(0); } loginThread = new LoginThread(this, socket); loginThread.start(); }
public static LoaderOptions parseArgs(String cmdArgs[]) { CommandLineParser parser = new GnuParser(); CmdLineOptions options = getCmdLineOptions(); try { CommandLine cmd = parser.parse(options, cmdArgs, false); if (cmd.hasOption(HELP_OPTION)) { printUsage(options); System.exit(0); } String[] args = cmd.getArgs(); if (args.length == 0) { System.err.println("Missing sstable directory argument"); printUsage(options); System.exit(1); } if (args.length > 1) { System.err.println("Too many arguments"); printUsage(options); System.exit(1); } String dirname = args[0]; File dir = new File(dirname); if (!dir.exists()) errorMsg("Unknown directory: " + dirname, options); if (!dir.isDirectory()) errorMsg(dirname + " is not a directory", options); LoaderOptions opts = new LoaderOptions(dir); opts.debug = cmd.hasOption(DEBUG_OPTION); opts.verbose = cmd.hasOption(VERBOSE_OPTION); opts.noProgress = cmd.hasOption(NOPROGRESS_OPTION); if (cmd.hasOption(RPC_PORT_OPTION)) opts.rpcPort = Integer.parseInt(cmd.getOptionValue(RPC_PORT_OPTION)); if (cmd.hasOption(USER_OPTION)) opts.user = cmd.getOptionValue(USER_OPTION); if (cmd.hasOption(PASSWD_OPTION)) opts.passwd = cmd.getOptionValue(PASSWD_OPTION); if (cmd.hasOption(INITIAL_HOST_ADDRESS_OPTION)) { String[] nodes = cmd.getOptionValue(INITIAL_HOST_ADDRESS_OPTION).split(","); try { for (String node : nodes) { opts.hosts.add(InetAddress.getByName(node.trim())); } } catch (UnknownHostException e) { errorMsg("Unknown host: " + e.getMessage(), options); } } else { System.err.println("Initial hosts must be specified (-d)"); printUsage(options); System.exit(1); } if (cmd.hasOption(IGNORE_NODES_OPTION)) { String[] nodes = cmd.getOptionValue(IGNORE_NODES_OPTION).split(","); try { for (String node : nodes) { opts.ignores.add(InetAddress.getByName(node.trim())); } } catch (UnknownHostException e) { errorMsg("Unknown host: " + e.getMessage(), options); } } // try to load config file first, so that values can be rewritten with other option values. // otherwise use default config. Config config; if (cmd.hasOption(CONFIG_PATH)) { File configFile = new File(cmd.getOptionValue(CONFIG_PATH)); if (!configFile.exists()) { errorMsg("Config file not found", options); } config = new YamlConfigurationLoader().loadConfig(configFile.toURI().toURL()); } else { config = new Config(); } opts.storagePort = config.storage_port; opts.sslStoragePort = config.ssl_storage_port; opts.throttle = config.stream_throughput_outbound_megabits_per_sec; opts.encOptions = config.client_encryption_options; opts.serverEncOptions = config.server_encryption_options; if (cmd.hasOption(THROTTLE_MBITS)) { opts.throttle = Integer.parseInt(cmd.getOptionValue(THROTTLE_MBITS)); } if (cmd.hasOption(SSL_TRUSTSTORE)) { opts.encOptions.truststore = cmd.getOptionValue(SSL_TRUSTSTORE); } if (cmd.hasOption(SSL_TRUSTSTORE_PW)) { opts.encOptions.truststore_password = cmd.getOptionValue(SSL_TRUSTSTORE_PW); } if (cmd.hasOption(SSL_KEYSTORE)) { opts.encOptions.keystore = cmd.getOptionValue(SSL_KEYSTORE); // if a keystore was provided, lets assume we'll need to use it opts.encOptions.require_client_auth = true; } if (cmd.hasOption(SSL_KEYSTORE_PW)) { opts.encOptions.keystore_password = cmd.getOptionValue(SSL_KEYSTORE_PW); } if (cmd.hasOption(SSL_PROTOCOL)) { opts.encOptions.protocol = cmd.getOptionValue(SSL_PROTOCOL); } if (cmd.hasOption(SSL_ALGORITHM)) { opts.encOptions.algorithm = cmd.getOptionValue(SSL_ALGORITHM); } if (cmd.hasOption(SSL_STORE_TYPE)) { opts.encOptions.store_type = cmd.getOptionValue(SSL_STORE_TYPE); } if (cmd.hasOption(SSL_CIPHER_SUITES)) { opts.encOptions.cipher_suites = cmd.getOptionValue(SSL_CIPHER_SUITES).split(","); } if (cmd.hasOption(TRANSPORT_FACTORY)) { ITransportFactory transportFactory = getTransportFactory(cmd.getOptionValue(TRANSPORT_FACTORY)); configureTransportFactory(transportFactory, opts); opts.transportFactory = transportFactory; } return opts; } catch (ParseException | ConfigurationException | MalformedURLException e) { errorMsg(e.getMessage(), options); return null; } }
public static void main(String[] args) { // Checks if no command line args were given by usej if (args.length <= 0) { System.out.println("No user specified!"); return; } // Sets the filename equal to the command line argument String filename = ""; String message = args[0]; try { // Creates an InetAddress using localhost InetAddress address = InetAddress.getByName("localhost"); // The byte buffer used for data the client is sending byte[] sdata = new byte[PACKET_SIZE]; // The byte buffer used for data the client is receiving byte[] rData = new byte[PACKET_SIZE]; // Puts "Sync" into the send Data sdata = ("SYNC" + message).getBytes(); DatagramSocket socket = new DatagramSocket(); // Socket timesout after 5 seconds to prevent infinite wait socket.setSoTimeout(5000); // Creates the packet and puts in the message DatagramPacket packet = new DatagramPacket(sdata, sdata.length, address, 3031); // Sends packet with the message to the server socket.send(packet); // Creates the recieve packet DatagramPacket rpacket = new DatagramPacket(rData, rData.length); socket.receive(rpacket); // Pulls the string out of the recieved packet String cmd1 = new String(rpacket.getData(), 0, rpacket.getLength()); // Checks if the server sent SYNACK if (cmd1.substring(0, 6).equals("SYNACK")) { String dirList = cmd1.substring(6); System.out.println(dirList); System.out.flush(); System.out.println( "Please type the file you wish to receive, or type " + "EXIT to close the server"); Scanner scan = new Scanner(System.in); filename = scan.next(); // Puts the file named into the Send Data sdata = filename.getBytes(); // Creates a Packet with the Filename packet = new DatagramPacket(sdata, sdata.length, address, 3031); socket.send(packet); } else return; // Checks if the filename is Exit. If so the client exits as well if (filename.equals("EXIT")) { System.out.println("Exit request sent."); return; } // Creates a local file to put the data recieved from the server in. socket.receive(rpacket); // Pulls the filename out of the recieved packet filename = new String(rpacket.getData(), 0, rpacket.getLength()); // Check if the first 7 characters are 'FILEACK', if so set file name // to the rest of the message if (filename.substring(0, 7).equals("FILEACK")) { filename = filename.substring(9 + message.length(), filename.length()); System.out.println("File name requested: " + filename); } else { // If no FILEACK, then the file specified was not valid System.out.println("Not a valid file!"); return; } File file = new File("local_" + filename); // Opens a FileOutputStream to use to write the data in the above file. FileOutputStream fos = new FileOutputStream(file); // Creates the receiving packet for data comming form the server System.out.println("Transfer started."); // The loop to received the packets of requested data. windowPackets = new DatagramPacket[MAX_SEQ]; CRC32 crc = new CRC32(); while (!done) { // Receives a packet sent from server socket.receive(rpacket); // Initialize arrays byte[] info = new byte[INT_SIZE]; byte[] code = new byte[CHECKSUM_SIZE]; byte[] data = new byte[rpacket.getLength() - SAC_SIZE]; byte[] data2 = new byte[rpacket.getLength() - CHECKSUM_SIZE]; // Split packet data into appropriate arrays System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE); System.arraycopy(rpacket.getData(), INT_SIZE, data, 0, rpacket.getLength() - SAC_SIZE); System.arraycopy(rpacket.getData(), 0, data2, 0, rpacket.getLength() - CHECKSUM_SIZE); System.arraycopy( rpacket.getData(), rpacket.getLength() - CHECKSUM_SIZE, code, 0, CHECKSUM_SIZE); // Convert seq num and other numbers from bytes to ints int packNum2 = ByteConverter.toInt(info, 0); int sCode = ByteConverter.toInt(code, 0); int packNum = ByteConverter.toInt(info, 0); // Reset and update crc for next packet crc.reset(); crc.update(data2, 0, data2.length); int cCode = (int) crc.getValue(); byte[] ackNum = ByteConverter.toBytes(packNum); ArrayList<Integer> expecting = new ArrayList<Integer>(); // Check for errors if (cCode == sCode) { // Create expected sequence numbers for (int i = 0; i < WINDOW_SIZE; i++) { if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ); else expecting.add(base + i); } // If packet number is base packet number if (packNum == base) { ackNum = ByteConverter.toBytes(packNum); packet = new DatagramPacket(ackNum, ackNum.length, address, 3031); socket.send(packet); // If last packet if (rpacket.getLength() == 0) { done = true; break; } // Write and move base forward fos.write(data, 0, data.length); base++; if (base == MAX_SEQ) base = 0; // update expected packets for (int i = 0; i < WINDOW_SIZE; i++) { if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ); else expecting.add(base + i); } // If the packet has data it writes it into the local file. // If this packet is smaller than the agree upon size then it knows // that the transfer is complete and client ends. if (rpacket.getLength() < PACKET_SIZE) { System.out.println("File transferred"); done = true; break; } // While there are packets in buffer, move packet to file while (windowPackets[base] != null) { DatagramPacket nextPacket = windowPackets[base]; windowPackets[base] = null; data = new byte[nextPacket.getLength() - SAC_SIZE]; System.arraycopy( nextPacket.getData(), INT_SIZE, data, 0, nextPacket.getLength() - SAC_SIZE); System.arraycopy(nextPacket.getData(), 0, info, 0, INT_SIZE); packNum = ByteConverter.toInt(info, 0); // If packet size is 0, then it is the last packet if (nextPacket.getLength() == 0) { System.out.println("File transferred"); done = true; break; } // Write and move base forward fos.write(data, 0, data.length); base++; if (base == MAX_SEQ) base = 0; expecting.clear(); // Update expected for (int i = 0; i < WINDOW_SIZE; i++) { if (base + i >= MAX_SEQ) expecting.add((base + i) - MAX_SEQ); else expecting.add(base + i); } // If the packet has data it writes it into the local file. // If this packet is smaller than the agree upon size then it knows // that the transfer is complete and client ends. if (nextPacket.getLength() < PACKET_SIZE) { System.out.println("File transferred"); done = true; break; } } } else if (expecting.contains(packNum)) { // If its expected, put it into buffer windowPackets[packNum] = rpacket; System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE); packNum = ByteConverter.toInt(info, 0); ackNum = ByteConverter.toBytes(packNum); packet = new DatagramPacket(ackNum, ackNum.length, address, 3031); socket.send(packet); } else { // If not expected, just ACK packet System.arraycopy(rpacket.getData(), 0, info, 0, INT_SIZE); packNum = ByteConverter.toInt(info, 0); ackNum = ByteConverter.toBytes(packNum); packet = new DatagramPacket(ackNum, ackNum.length, address, 3031); socket.send(packet); } } else { // CRC found error with packet System.out.println("ERROR"); } } // transfer is done System.out.println("File length - " + file.length()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { InetAddress serverIp = null; Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); String hostname = "", clientIp = "", userAgent = ""; try { serverIp = InetAddress.getLocalHost(); hostname = serverIp.getHostName(); clientIp = request.getHeader("X-FORWARDED-FOR"); if (clientIp == null) { clientIp = request.getRemoteAddr(); } userAgent = request.getHeader("user-agent"); } catch (UnknownHostException e) { e.printStackTrace(); } response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.println("<html>"); writer.println("<head>"); writer.println("<title>Sample Application Page</title>"); writer.println("</head>"); writer.println("<body bgcolor=white>"); writer.println("<table border=\"0\">"); writer.println("<tr>"); writer.println("<td>"); writer.println("<h1>Sample Application</h1>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); // writer.println("Server IP address: <strong>" + serverIp.getHostAddress() + // "</strong>"); writer.println("Server IP addresses: <strong>"); while (interfaces.hasMoreElements()) { NetworkInterface n = (NetworkInterface) interfaces.nextElement(); Enumeration inetAddresses = n.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress address = (InetAddress) inetAddresses.nextElement(); if (address.getHostAddress().substring(0, 6).compareTo("10.42.") == 0) writer.println(address.getHostAddress() + " "); } } writer.println("</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); writer.println("Server Hostname: <strong>" + hostname + "</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); writer.println("Your current IP address: <strong>" + clientIp + "</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("<tr>"); writer.println("<td>"); writer.println("Your current User-Agent: <strong>" + userAgent + "</strong>"); writer.println("</td>"); writer.println("</tr>"); writer.println("</table>"); writer.println("</body>"); writer.println("</html>"); }
public static void main(String[] args) throws EOFException { queue = new ArrayList<Traffic>(); ObjectInputStream OISforTG = null; ObjectOutputStream OOSforLot = null; System.out.print("login?"); sc = new Scanner(System.in); String input = sc.nextLine(); if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) { // System.out.println(ConnectionData.ipTG+" "+ConnectionData.portForTG); try { // socketForManager = new Socket(ConnectionData.ipMani, ConnectionData.portForManager); socketForTG = new Socket(ConnectionData.ipTG, ConnectionData.portForTG); socketForTime = new Socket(ConnectionData.ipTG, ConnectionData.portForTime); socketForParkingLot = new Socket(ConnectionData.ipLot, ConnectionData.portForLot); System.out.println("Connected"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } receiverForManager RFM = new receiverForManager(); Thread ThreadRFM = new Thread(RFM); ThreadRFM.start(); trafficReceiver trafficRec = new trafficReceiver(); Thread ThreadTraffic = new Thread(trafficRec); ThreadTraffic.start(); try { OOSforLot = new ObjectOutputStream(socketForParkingLot.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException npe) { npe.printStackTrace(); } timeReader TR = new timeReader(); Thread thread = new Thread(TR); thread.start(); carReturned CR = new carReturned(); Thread thread1 = new Thread(CR); thread1.start(); // System.out.println("reach1"); while (true) { try { if (Token > 0 && queue.size() > 0) { Token--; System.out.println(Token); OOSforLot.writeObject(queue.get(0)); } else if (Token == 0 && queue.size() > 0) { String carOrig = queue.get(0).getGeneratedTime(); Integer carOrigInt[] = utils.timeConverter(carOrig); int Orig = (carOrigInt[0] * 3600) + (carOrigInt[1] * 60); int Curren = (currentTime[0] * 3600) + (currentTime[1] * 60); if ((Curren - Orig) > 600) { // need to something... // // // // } else { System.out.println("Token: " + Token + " queue Size: " + queue.size()); continue; } } } catch (IOException e) { e.printStackTrace(); } } } }
public JavaGame(String[] args) { this.args = args; updater = new Updater(this); highscore = new Highscore(this); eventHandler = new EventHandler(this); eventHandler.registerTestEvents(); setTitle("Survive-JavaGame"); // Fenstertitel setzen setSize(1200, 900); // Fenstergröße einstellen addWindowListener(new WindowListener()); setLocationRelativeTo(null); try { arg = args[0]; } catch (ArrayIndexOutOfBoundsException e) { arg = "nothing"; } if (arg.equals("fullscreen")) { setUndecorated(true); // "Vollbild" setSize( (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() - 200, (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth()); setLocation(0, 0); } setVisible(true); setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); try { /*URI Path = URLDecoder.decode(getClass().getClassLoader().getResource("texture").toURI();//, "UTF-8"); //Pfad zu den Resourcen File F = new File(Path); basePath = F; System.out.println(basePath); */ File File = new File((System.getenv("APPDATA"))); basePath = new File(File, "/texture"); backgroundTexture = new File(basePath, "/hintergrund.jpg"); } catch (Exception ex) { ex.printStackTrace(); } try { backgroundImage = ImageIO.read(backgroundTexture); } catch (IOException exeption) { } if (soundan) { currentVolume = 80; } // end of if dbImage = createImage(1920, 1080); // dbGraphics = dbImage.getGraphics(); // Texturen Liste // Ebenen Liste ebenen[0][0] = 91; ebenen[0][1] = 991; // Main Ebene: Kann nicht durchschrittenwerden indem down gedrückt wird ebenen[0][2] = 563; ebenen[1][0] = 387; // x1 ebenen[1][1] = 524; // x2 ebenen[1][2] = 454; // y ebenen[2][0] = 525; ebenen[2][1] = 645; ebenen[2][2] = 350; ebenen[3][0] = 246; ebenen[3][1] = 365; ebenen[3][2] = 351; ebenen[4][0] = 760; ebenen[4][1] = 870; ebenen[4][2] = 294; ebenen[5][0] = 835; ebenen[5][1] = 969; ebenen[5][2] = 441; // Spieler // I'm in Space! SPACE! player[1] = new Player( (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]), 0, false, 67, 100, texture[0], shottexture[0], KeyEvent.VK_A, KeyEvent.VK_D, KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_Q, 1, 35, highscore.getName(1)); player[2] = new Bot( (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]), 0, false, 67, 100, texture[1], shottexture[1], KeyEvent.VK_J, KeyEvent.VK_L, KeyEvent.VK_I, KeyEvent.VK_K, KeyEvent.VK_U, 2, 35, highscore.getName(1)); player[3] = new Bot( (int) (Math.random() * (ebenen[0][1] - ebenen[0][0]) + ebenen[0][0]), 0, false, 67, 100, texture[2], shottexture[2], KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_ENTER, 3, 35, highscore.getName(1)); player[1].laden(this); player[2].laden(this); player[3].laden(this); this.addKeyListener(player[1]); this.addKeyListener(player[2]); this.addKeyListener(player[3]); this.addKeyListener(this); int result; Object[] options = {"SinglePlayer", "MultiPlayer"}; if (arg.equals("dedicated")) { Server server = new Server(); this.server = true; setVisible(false); } else { if ((result = JOptionPane.showOptionDialog( null, "Treffen Sie eine Auswahl", "Alternativen", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0])) == 1) { client = new Client(this); online = true; while ((onlinename = JOptionPane.showInputDialog( null, "Geben Sie Ihren Namen ein", "Eine Eingabeaufforderung", JOptionPane.PLAIN_MESSAGE)) .isEmpty() && onlinename != null) {} Object[] optionsmp = {"Host", "Client"}; if ((result = JOptionPane.showOptionDialog( null, "Treffen Sie eine Auswahl", "Alternativen", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, optionsmp, optionsmp[0])) == 0) { Server server = new Server(); this.server = true; } else if (online) { while ((serveradresse = JOptionPane.showInputDialog( null, "Geben Sie die Serveradresse ein", "Eine Eingabeaufforderung", JOptionPane.PLAIN_MESSAGE)) .isEmpty() && serveradresse != null) {} } } } if (!arg.equals("dedicated")) { gamerunner = new GameRunner(player, this); DamageLogig = new damageLogig(gamerunner); } if (online) { try { client.initialise(serveradresse, 9876); client.start(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // end of init
/** * connect: connect to the master * * @return: true for success and false for failure */ protected boolean connect() { boolean connected = true; try { _sock = new Socket(_serverIP, _serverPort); _out = new PrintWriter(_sock.getOutputStream(), true); _in = new BufferedReader(new InputStreamReader(_sock.getInputStream())); String reply = sendAll(); if (!reply.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) { /* Tokenize */ StringTokenizer st = new StringTokenizer(reply); if (st.nextToken().equals(ProtocolConstants.PACK_STR_ERRMES_HEAD)) { _elog(st.nextToken()); return false; } } _userSock = new Socket(_serverIP, _serverPort); _userOut = new PrintWriter(_userSock.getOutputStream(), true); _userIn = new BufferedReader(new InputStreamReader(_userSock.getInputStream())); String replyUser = sendUserID(); if (!replyUser.equals(ProtocolConstants.PACK_STR_CONFIRM_HEAD)) { throw new Exception("Not confirmed"); } } catch (UnknownHostException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } connected = false; } catch (IOException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } connected = false; } catch (Exception e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } connected = false; } if (!connected) { return connected; } if (!connected) { /* Remove the pair of socket */ _sock = null; _in = null; _out = null; _userSock = null; _userOut = null; _userIn = null; } return connected; }