public static void main(String[] args) throws Exception { startServer(); try { doClientSide(); } catch (SocketException e) { if (!e.getMessage().equalsIgnoreCase("Socket closed")) { throw new Exception("Received a wrong exception message: " + e.getMessage()); } System.out.println("PASSED: received the right exception message: " + e.getMessage()); } if (serverException != null) { throw serverException; } }
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(); } }
/** * Initializes and binds a socket that on a random port number. The method would try to bind on a * random port and retry 5 times until a free port is found. * * @return the socket that we have initialized on a randomport number. */ private DatagramSocket initRandomPortSocket() { DatagramSocket resultSocket = null; String bindRetriesStr = NetaddrActivator.getConfigurationService().getString(BIND_RETRIES_PROPERTY_NAME); int bindRetries = 5; if (bindRetriesStr != null) { try { bindRetries = Integer.parseInt(bindRetriesStr); } catch (NumberFormatException ex) { logger.error( bindRetriesStr + " does not appear to be an integer. " + "Defaulting port bind retries to " + bindRetries, ex); } } int currentlyTriedPort = NetworkUtils.getRandomPortNumber(); // we'll first try to bind to a random port. if this fails we'll try // again (bindRetries times in all) until we find a free local port. for (int i = 0; i < bindRetries; i++) { try { resultSocket = new DatagramSocket(currentlyTriedPort); // we succeeded - break so that we don't try to bind again break; } catch (SocketException exc) { if (exc.getMessage().indexOf("Address already in use") == -1) { logger.fatal( "An exception occurred while trying to create" + "a local host discovery socket.", exc); resultSocket = null; return null; } // port seems to be taken. try another one. logger.debug("Port " + currentlyTriedPort + " seems in use."); currentlyTriedPort = NetworkUtils.getRandomPortNumber(); logger.debug("Retrying bind on port " + currentlyTriedPort); } } return resultSocket; }
/** * Main method keeps waiting for request and do math operation accordingly * * @param args */ public static void main(String args[]) { DatagramSocket aSocket = null; try { aSocket = new DatagramSocket(6789); byte[] buffer = new byte[1000]; while (true) { DatagramPacket request = new DatagramPacket(buffer, buffer.length); aSocket.receive(request); // receive byte array of equation and put it in string String equation = new String(request.getData()); String answer = ""; String[] split = equation.split(" "); // parse to integer and calculate String op = split[1]; double var1 = Double.parseDouble(split[0]); double var2 = Double.parseDouble(split[2]); if (op.equals("+")) { answer = Double.toString(var1 + var2); } else if (op.equals("-")) { answer = Double.toString(var1 - var2); } else if (op.toLowerCase().equals("X") || op.toLowerCase().equals("x")) { answer = Double.toString(var1 * var2); } else if (op.equals("/")) { answer = Double.toString(var1 / var2); } // send answer back DatagramPacket reply = new DatagramPacket( answer.getBytes(), (answer.getBytes()).length, request.getAddress(), request.getPort()); aSocket.send(reply); } } catch (SocketException e) { System.out.println("Socket: " + e.getMessage()); } catch (IOException e) { System.out.println("IO: " + e.getMessage()); } finally { if (aSocket != null) { aSocket.close(); } } }
public void run() { while (Thread.currentThread() == thread) { try { Socket socket = server.accept(); Client client = new Client(parent, socket); if (clientValidationMethod != null) { try { clientValidationMethod.invoke(parent, new Object[] {this, client}); } catch (Exception e) { // System.err.println("Disabling serverEvent() for port " + port); e.printStackTrace(); } } if (client.active()) { synchronized (clients) { addClient(client); if (serverEventMethod != null) { try { serverEventMethod.invoke(parent, new Object[] {this, client}); } catch (Exception e) { // System.err.println("Disabling serverEvent() for port " + port); e.printStackTrace(); } } } } } catch (SocketException e) { // thrown when server.close() is called and server is waiting on accept System.err.println("Server SocketException: " + e.getMessage()); thread = null; } catch (IOException e) { // errorMessage("run", e); e.printStackTrace(); thread = null; } try { Thread.sleep(8); } catch (InterruptedException ex) { } } }
@Override public void run() { while (true) { try { String wsName = EncodeDecode.decodeString(receive()); Integer paramCnt = Integer.parseInt(EncodeDecode.decodeString(receive())); String params[] = new String[paramCnt]; for (int i = 0; i < paramCnt; i++) { params[i] = EncodeDecode.decodeString(receive()); } String result = internal_call(wsName, params); send(EncodeDecode.encode(result)); } catch (NumberFormatException e) { logger.info("number format error"); return; } catch (SocketException e) { logger.info("socket " + e.getMessage()); return; } } }
public boolean makeconnection() { if (serversoc == null || serversoc.isClosed()) { try { serversoc = new ServerSocket(portnum); serversoc.setSoTimeout(0); } catch (IOException ex) { logger.warning(ex.getMessage()); } } try { System.out.println("server waiting"); mysocket = serversoc.accept(); in = mysocket.getInputStream(); out = mysocket.getOutputStream(); oos = new ObjectOutputStream(out); ois = new ObjectInputStream(in); System.out.println("connection established"); waitforreceivingdata(); return true; } catch (SocketException ex) { logger.warning(ex.getMessage()); return false; } catch (IOException ex) { logger.warning(ex.getMessage()); return false; } catch (Exception ex) { logger.warning(ex.getMessage()); return false; } }
/** * Create a multicast socket and join the multicast group. This method creates a multicast socket * that is used to broadcast The <CODE>DiscoveryResponder</CODE> will then join the multicast * group and send a join message. This method has no effect if the <CODE>DiscoveryResponder</CODE> * is <CODE>ONLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>. * * @exception IOException The creation of the Multicast socket failed. */ public void start() throws IOException { if (state == OFFLINE) { changeState(STARTING); if (cmf == null) { if (logger.finerOn()) { logger.finer("start ", "Can't start discoveryResponder: JDMK MBeanServer is not set"); } return; } // ---------------- // Create a new obj to receive multicast msg ; // ---------------- try { if (logger.finerOn()) { logger.finer("start ", "Create a new responder"); } responder = new ActualResponder(multicastGroup, multicastPort, getTimeToLive(), cmf, spy, this); if (local != null) { responder.setLocalHost(local); } // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001 if (usrInet != null) { responder.setInterface(usrInet); if (logger.finerOn()) { logger.finer("start ", "set interface to " + usrInet); } } // end of NPCTE fix for bugId 4499338 if (noEvent != null) responder.noEvent(); if (logger.finerOn()) { logger.finer("start ", "call responder connect"); } responder.connectToGroup(); // ---------------- // Create a new thread to receive multicast msg ; // ---------------- // responderThread = cmf.getThreadAllocatorSrvIf().obtainThread(responderObjectName, // responder); responderThread = new Thread(responder); responderThread.setName("Multicast responder"); // ---------------- // Start thread // ---------------- responderThread.start(); // ---------------- // Update state // ---------------- // changeState(ONLINE) ; } catch (SocketException e) { if (logger.finestOn()) { logger.finest("start", e); } throw new IOException(e.getMessage()); } catch (IOException e) { // ------------------------ // Keep exception for us // ------------------------ if (logger.finestOn()) { logger.finest("start ", e); } throw e; } catch (NullPointerException e) { // ------------------------ // the set group did not worked // ------------------------ if (logger.finestOn()) { logger.finest("start ", e); } throw new IOException(e.getMessage()); } } else { if (logger.finerOn()) { logger.finer("start ", "Responder is not OFFLINE"); } } }