Java Code Examples for java.net.SocketException
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project activemq-apollo, under directory /apollo-util/src/test/scala/org/apache/activemq/apollo/util/.
Source file: SocketProxy.java

public Acceptor(ServerSocket serverSocket,URI uri){ socket=serverSocket; target=uri; pause.set(new CountDownLatch(0)); try { socket.setSoTimeout(ACCEPT_TIMEOUT_MILLIS); } catch ( SocketException e) { e.printStackTrace(); } }
Example 2
From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/util/.
Source file: ActivitiStreamingWebScript.java

/** * Streams an input stream to the webscript response * @param res The response to stream the response to * @param inputStream The input stream conatining the data * @param modified The date and time when the streamed data was modified * @param eTag The cache eTag to use for the data * @param attachFileName Will if provided be used as a attach file name header to improve the chances ofbeing opened by an external program * @param mimetype The mimetype of the contents * @throws IOException */ protected void streamResponse(WebScriptResponse res,InputStream inputStream,Date modified,String eTag,boolean attach,String attachFileName,String mimetype) throws IOException { if (attach) { String headerValue="attachment"; if (attachFileName != null && attachFileName.length() > 0) { headerValue+="; filename=" + attachFileName; } res.setHeader("Content-Disposition",headerValue); } if (mimetype != null) { res.setContentType(mimetype); } Cache cache=new Cache(); cache.setNeverCache(false); cache.setMustRevalidate(true); cache.setMaxAge(0L); cache.setLastModified(modified); if (eTag != null) { cache.setETag(eTag); } res.setCache(cache); try { byte[] buffer=new byte[0xFFFF]; for (int len; (len=inputStream.read(buffer)) != -1; ) res.getOutputStream().write(buffer,0,len); } catch ( SocketException e) { } }
Example 3
From project airlift, under directory /node/src/main/java/io/airlift/node/.
Source file: NodeInfo.java

private static List<NetworkInterface> getGoodNetworkInterfaces(){ ImmutableList.Builder<NetworkInterface> builder=ImmutableList.builder(); try { for ( NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) { try { if (!networkInterface.isLoopback() && networkInterface.isUp()) { builder.add(networkInterface); } } catch ( Exception ignored) { } } } catch ( SocketException ignored) { } return builder.build(); }
Example 4
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/.
Source file: SocketHttpClientConnection.java

public void setSocketTimeout(int timeout){ assertOpen(); if (this.socket != null) { try { this.socket.setSoTimeout(timeout); } catch ( SocketException ignore) { } } }
Example 5
From project anarchyape, under directory /src/main/java/ape/.
Source file: DenialOfServiceRunner.java

public void run(){ long currentTime=System.currentTimeMillis(); long endTime=currentTime + (duration * 1000); while (System.currentTimeMillis() < endTime) { try { Socket net=new Socket(target,port); sendRawLine("GET / HTTP/1.1",net); } catch ( UnknownHostException e) { System.out.println("Could not resolve hostname."); e.printStackTrace(); Main.logger.info("Could not resolve hostname."); Main.logger.info(e); break; } catch ( ConnectException e) { System.out.println("The connection was refused. Make sure that port " + port + " is open and receiving connections on host "+ target); Main.logger.info("The connection was refused. Make sure that port " + port + " is open and receiving connections on host "+ target); e.printStackTrace(); Main.logger.info(e); break; } catch ( SocketException e) { if (Main.VERBOSE) { System.out.println("VERBOSE: Client says too many files open. This is expected in a DoS attack. Continuing..."); e.printStackTrace(); } } catch ( IOException e) { e.printStackTrace(); Main.logger.info(e); break; } } }
Example 6
From project andlytics, under directory /src/com/github/andlyticsproject/admob/.
Source file: AdmobRequest.java

private static void handleNonJsonException(Exception e,String sb) throws NetworkException, AdmobGenericException, AdmobInvalidTokenException { if (e instanceof SocketException || e instanceof UnknownHostException || e instanceof IOException|| e instanceof NetworkException) { throw new NetworkException(e); } else if (e instanceof AdmobInvalidTokenException) { throw (AdmobInvalidTokenException)e; } else { throw new AdmobGenericException(e,sb); } }
Example 7
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/jtwitter/.
Source file: URLConnectionHttpClient.java

/** * Throw an exception if the connection failed * @param connection */ final void processError(HttpURLConnection connection){ try { int code=connection.getResponseCode(); if (code == 200) return; URL url=connection.getURL(); String error=processError2_reason(connection); if (code == 401) { if (error.contains("Basic authentication is not supported")) throw new TwitterException.UpdateToOAuth(); throw new TwitterException.E401(error + "\n" + url+ " ("+ (name == null ? "anonymous" : name)+ ")"); } if (code == 403) { processError2_403(url,error); } if (code == 404) { if (error != null && error.contains("deleted")) throw new TwitterException.SuspendedUser(error + "\n" + url); throw new TwitterException.E404(error + "\n" + url); } if (code == 406) throw new TwitterException.E406(error + "\n" + url); if (code == 413) throw new TwitterException.E413(error + "\n" + url); if (code == 416) throw new TwitterException.E416(error + "\n" + url); if (code == 420) throw new TwitterException.TooManyLogins(error + "\n" + url); if (code >= 500 && code < 600) throw new TwitterException.E50X(error + "\n" + url); processError2_rateLimit(connection,code,error); throw new TwitterException(code + " " + error+ " "+ url); } catch ( SocketTimeoutException e) { URL url=connection.getURL(); throw new TwitterException.Timeout(timeout + "milli-secs for " + url); } catch ( ConnectException e) { URL url=connection.getURL(); throw new TwitterException.Timeout(url.toString()); } catch ( SocketException e) { throw new TwitterException.E50X(e.toString()); } catch ( IOException e) { throw new TwitterException(e); } }
Example 8
From project android-xbmcremote, under directory /src/org/xbmc/eventclient/.
Source file: Packet.java

/** * Sends this packet to the EventServer * @param adr Address of the EventServer * @param port Port of the EventServer * @throws IOException */ public void send(final InetAddress adr,final int port){ new Thread(){ @Override public void run(){ super.run(); int maxseq=getNumPackets(); DatagramSocket s; try { s=new DatagramSocket(); } catch ( SocketException e) { Log.e(TAG,"Error opening data socket: " + e.getMessage(),e); return; } try { for (int seq=1; seq <= maxseq; seq++) { byte[] pack=getUDPMessage(seq); DatagramPacket p=new DatagramPacket(pack,pack.length); p.setAddress(adr); p.setPort(port); try { s.send(p); } catch ( IOException e) { Log.e(TAG,"Error sending UDP packet: " + e.getMessage(),e); } } } finally { s.close(); } } } .start(); }
Example 9
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: Client.java

private void setSocketOptions(Socket aSocket) throws SocketException { aSocket.setTcpNoDelay(true); if (keepAlive > 0) { aSocket.setKeepAlive(true); aSocket.setSoTimeout(keepAlive); } }
Example 10
From project android_8, under directory /src/com/defuzeme/network/.
Source file: Broadcaster.java

@Override protected void onPreExecute(){ DefuzeMe.Gui.showProgress(string.SearchingForClients); try { this._address=InetAddress.getByName(Settings._BCastSendAddress); this._rSocket=new MulticastSocket(Settings._BCastRecvPort); this._sSocket=new DatagramSocket(); this._rSocket.joinGroup(InetAddress.getByName(Settings._BCastRecvAddress)); this._rSocket.setSoTimeout(Settings._TimeOut); } catch ( UnknownHostException exception) { Log.w(this.getClass().getName(),"Unknown host : " + exception.toString()); } catch ( SocketException exception) { Log.e(this.getClass().getName(),"Socket exception : " + exception.toString()); } catch ( IOException exception) { Log.w(this.getClass().getName(),"IO Exception : " + exception.toString()); } }
Example 11
From project Arecibo, under directory /event/src/main/java/com/ning/arecibo/event/receiver/.
Source file: DatagramSocketProvider.java

public DatagramSocket get(){ try { DatagramSocket socket=new DatagramSocket(new InetSocketAddress(config.getHost(),config.getPort())); return socket; } catch ( SocketException e) { throw new RuntimeException(e); } }
Example 12
From project AutobahnAndroid, under directory /Autobahn/src/de/tavendo/autobahn/.
Source file: WebSocketReader.java

/** * Run the background reader thread loop. */ @Override public void run(){ if (DEBUG) Log.d(TAG,"running"); try { mFrameBuffer.clear(); do { int len=mSocket.read(mFrameBuffer); if (len > 0) { while (consumeData()) { } } else if (len < 0) { if (DEBUG) Log.d(TAG,"run() : ConnectionLost"); notify(new WebSocketMessage.ConnectionLost()); mStopped=true; } } while (!mStopped); } catch ( WebSocketException e) { if (DEBUG) Log.d(TAG,"run() : WebSocketException (" + e.toString() + ")"); notify(new WebSocketMessage.ProtocolViolation(e)); } catch ( SocketException e) { if (DEBUG) Log.d(TAG,"run() : SocketException (" + e.toString() + ")"); notify(new WebSocketMessage.ConnectionLost()); ; } catch ( Exception e) { if (DEBUG) Log.d(TAG,"run() : Exception (" + e.toString() + ")"); notify(new WebSocketMessage.Error(e)); } finally { mStopped=true; } if (DEBUG) Log.d(TAG,"ended"); }
Example 13
From project autopsy, under directory /KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/.
Source file: Server.java

/** * Tests if there's a Solr server running by sending it a core-status request. * @return false if the request failed with a connection error, otherwisetrue */ synchronized boolean isRunning() throws KeywordSearchModuleException { try { CoreAdminRequest.getStatus(null,solrServer); logger.log(Level.INFO,"Solr server is running"); } catch ( SolrServerException ex) { Throwable cause=ex.getRootCause(); if (cause instanceof ConnectException || cause instanceof SocketException || cause instanceof NoHttpResponseException) { logger.log(Level.INFO,"Solr server is not running, cause: " + cause.getMessage()); return false; } else { throw new KeywordSearchModuleException("Error checking if Solr server is running",ex); } } catch ( IOException ex) { throw new KeywordSearchModuleException("Error checking if Solr server is running",ex); } return true; }
Example 14
From project baseunits, under directory /src/test/java/jp/xet/baseunits/tests/.
Source file: CannedResponseServer.java

private Runnable getServerConnectionProcessor(){ return new Runnable(){ @Override public void run(){ try { while (getKeepProcessing()) { Socket client=socket.accept(); serveCannedResponse(client); } } catch ( SocketException ex) { } catch ( Exception ex) { throw new RuntimeException(ex); } } } ; }
Example 15
From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/event/.
Source file: EventListenerClient.java

@Override public void run(){ if (STREAM != null) { Event event; while (!_stopRequested) { event=null; try { event=Event.create(readObject()); } catch ( SocketException e) { if (!_stopRequested) { e.printStackTrace(); close(); } } if (event != null) { add(event); } } } }
Example 16
From project BioMAV, under directory /ParrotControl/JavaDroneControl/src/nl/ru/ai/projects/parrot/dronecontrol/javadronecontrol/.
Source file: DroneGroundStation.java

public DroneGroundStation() throws SocketException { controlCommandInterface=new ATControlCommandInterface(); droneConfigurationChannel=new DroneConfigurationChannel(controlCommandInterface); vision=new VisionStandin(); navdataChannel=new NavdataChannel(droneConfigurationChannel); navdataChannel.addNavdataChannelObserver(this); }
Example 17
From project Cafe, under directory /webapp/src/org/openqa/selenium/net/.
Source file: DefaultNetworkInterfaceProvider.java

public DefaultNetworkInterfaceProvider(){ Enumeration<java.net.NetworkInterface> interfaces=null; try { interfaces=java.net.NetworkInterface.getNetworkInterfaces(); } catch ( SocketException e) { throw new WebDriverException(e); } List<NetworkInterface> result=new ArrayList<NetworkInterface>(); while (interfaces.hasMoreElements()) { result.add(createInterface(interfaces.nextElement())); } this.cachedInterfaces=Collections.unmodifiableList(result); }
Example 18
From project cas, under directory /cas-server-support-x509/src/test/java/org/jasig/cas/adaptors/x509/util/.
Source file: MockWebServer.java

public void run(){ while (this.running) { try { writeResponse(this.serverSocket.accept()); } catch ( SocketException se) { System.out.println("Stopping on socket close."); this.running=false; } catch ( IOException ioe) { ioe.printStackTrace(); } } }
Example 19
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/controller/.
Source file: ChukwaAgentController.java

/** * Registers this {@link Adaptor} with the agent running at the specifiedhostname and portno * @return The id of the this {@link Adaptor}, assigned by the agent upon successful registration * @throws IOException */ String register() throws IOException { Socket s=new Socket(hostname,portno); try { s.setSoTimeout(60000); } catch ( SocketException e) { log.warn("Error while settin soTimeout to 60000"); e.printStackTrace(); } PrintWriter bw=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); if (id != null) bw.println("ADD " + id + " = "+ className+ " "+ appType+ " "+ params+ " "+ offset); else bw.println("ADD " + className + " "+ appType+ " "+ params+ " "+ offset); bw.flush(); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String resp=br.readLine(); if (resp != null) { String[] fields=resp.split(" "); if (fields[0].equals("OK")) { id=fields[fields.length - 1]; } } s.close(); return id; }
Example 20
From project cloudify, under directory /dsl/src/main/java/org/cloudifysource/dsl/internal/context/.
Source file: IsLocalCloudUtils.java

/** * @param ip - the ip to check if it refers to the local machine. * @return true - if the specified ip is the local mahcine * @see "http://stackoverflow.com/questions/2406341/how-to-check-if-an-ip-address-is-the-local-host-on-a-multi-homed-system" */ public static boolean isThisMyIpAddress(final String ip){ InetAddress addr; try { addr=InetAddress.getByName(ip); } catch ( final UnknownHostException e) { return false; } if (addr.isAnyLocalAddress() || addr.isLoopbackAddress()) { return true; } try { return NetworkInterface.getByInetAddress(addr) != null; } catch ( final SocketException e) { return false; } }
Example 21
From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/.
Source file: NetUtil.java

@Override public boolean apply(final InetAddress input){ try { return input.isLoopbackAddress() || input.isAnyLocalAddress() || NetworkInterface.getByInetAddress(input) != null; } catch ( final SocketException se) { logger.error("Exception retrieving network interface for address[" + input + "]",se); return false; } }
Example 22
From project connectbot, under directory /src/sk/vx/connectbot/transport/.
Source file: Telnet.java

@Override public void write(byte[] buffer) throws IOException { try { if (os != null) os.write(buffer); } catch ( SocketException e) { bridge.dispatchDisconnect(false); } }
Example 23
From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/.
Source file: DatabaseIndexer.java

public void run(){ if (closed) { throw new IllegalStateException("closed!"); } try { init(); } catch ( final Exception e) { logger.warn("Exiting after init() raised exception.",e); close(); return; } try { try { req=database.getChangesRequest(since); logger.info("Indexing from update_seq " + since); client.execute(req,this); } finally { close(); } } catch ( final SocketException e) { } catch ( final Exception e) { logger.warn("Exiting due to exception.",e); close(); } }
Example 24
From project crash, under directory /shell/telnet/src/main/java/org/crsh/telnet/term/.
Source file: TelnetIO.java

public int read() throws IOException { try { return termIO.read(); } catch ( EOFException e) { return TerminalIO.HANDLED; } catch ( SocketException e) { return TerminalIO.HANDLED; } }
Example 25
From project curator, under directory /curator-x-discovery/src/main/java/com/netflix/curator/x/discovery/.
Source file: ServiceInstanceBuilder.java

/** * based on http://pastebin.com/5X073pUc <p> Returns all available IP addresses. <p> In error case or if no network connection is established, we return an empty list here. <p> Loopback addresses are excluded - so 127.0.0.1 will not be never returned. <p> The "primary" IP might not be the first one in the returned list. * @return Returns all IP addresses (can be an empty list in error caseor if network connection is missing). * @since 0.1.0 * @throws SocketException errors */ public static Collection<InetAddress> getAllLocalIPs() throws SocketException { List<InetAddress> listAdr=Lists.newArrayList(); Enumeration<NetworkInterface> nifs=NetworkInterface.getNetworkInterfaces(); if (nifs == null) return listAdr; while (nifs.hasMoreElements()) { NetworkInterface nif=nifs.nextElement(); Enumeration<InetAddress> adrs=nif.getInetAddresses(); while (adrs.hasMoreElements()) { InetAddress adr=adrs.nextElement(); if (adr != null && !adr.isLoopbackAddress() && (nif.isPointToPoint() || !adr.isLinkLocalAddress())) { listAdr.add(adr); } } } return listAdr; }
Example 26
From project cw-advandroid, under directory /SystemServices/ClipIP/src/com/commonsware/android/clipip/.
Source file: IPClipper.java

public String getLocalIPAddress() throws SocketException { Enumeration<NetworkInterface> nics=NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface intf=nics.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr=addrs.nextElement(); if (!addr.isLoopbackAddress()) { return (addr.getHostAddress().toString()); } } } return (null); }
Example 27
From project cw-omnibus, under directory /SystemServices/ClipIP/src/com/commonsware/android/clipip/.
Source file: IPClipper.java

public String getLocalIPAddress() throws SocketException { Enumeration<NetworkInterface> nics=NetworkInterface.getNetworkInterfaces(); while (nics.hasMoreElements()) { NetworkInterface intf=nics.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr=addrs.nextElement(); if (!addr.isLoopbackAddress()) { return (addr.getHostAddress().toString()); } } } return (null); }
Example 28
From project cxf-dosgi, under directory /dsw/cxf-dsw/src/main/java/org/apache/cxf/dosgi/dsw/handlers/.
Source file: AbstractConfigurationHandler.java

/** * Utility method that delegates to the methods of NetworkInterface to determine addresses for this machine. * @return InetAddress[] - all addresses found from the NetworkInterfaces * @throws UnknownHostException - if there is a problem determining addresses */ private static InetAddress[] getAllLocalUsingNetworkInterface() throws UnknownHostException { ArrayList addresses=new ArrayList(); Enumeration e=null; try { e=NetworkInterface.getNetworkInterfaces(); } catch ( SocketException ex) { throw new UnknownHostException("127.0.0.1"); } while (e.hasMoreElements()) { NetworkInterface ni=(NetworkInterface)e.nextElement(); for (Enumeration e2=ni.getInetAddresses(); e2.hasMoreElements(); ) { addresses.add(e2.nextElement()); } } InetAddress[] iAddresses=new InetAddress[addresses.size()]; for (int i=0; i < iAddresses.length; i++) { iAddresses[i]=(InetAddress)addresses.get(i); } return iAddresses; }
Example 29
From project daap, under directory /src/main/java/org/ardverk/daap/bio/.
Source file: DaapAudioResponseBIO.java

public boolean write() throws IOException { try { if (!headerWritten) { try { out.write(header,0,header.length); out.flush(); headerWritten=true; } catch ( IOException err) { throw err; } } return stream(); } catch ( SocketException err) { throw new DaapStreamException(err); } finally { close(); } }
Example 30
From project dawn-isencia, under directory /com.isencia.passerelle.commons.ume/src/main/java/com/isencia/message/net/.
Source file: DatagramReceiverChannel.java

public void open() throws ChannelException { if (logger.isTraceEnabled()) logger.trace("open() - entry"); if (socket == null) { try { socket=new DatagramSocket(getPort()); } catch ( SocketException e) { logger.error("open() - Socket construction failed on port " + port,e); throw new ChannelException("Socket construction failed on port " + port); } } super.open(); if (logger.isTraceEnabled()) logger.trace("open() - exit"); }
Example 31
From project dcm4che, under directory /dcm4che-net/src/main/java/org/dcm4che/net/.
Source file: Connection.java

private void setSocketSendOptions(Socket s) throws SocketException { int size=s.getSendBufferSize(); if (sendBufferSize == 0) { sendBufferSize=size; } else if (sendBufferSize != size) { s.setSendBufferSize(sendBufferSize); sendBufferSize=s.getSendBufferSize(); } if (s.getTcpNoDelay() != tcpNoDelay) { s.setTcpNoDelay(tcpNoDelay); } }
Example 32
From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/messagetransport/tcp/.
Source file: TcpReceiver.java

public TcpDestination doGetDestination() throws MessageTransportException { try { InetAddress inetAddress=useLocalhost ? InetAddress.getLocalHost() : TcpTransport.getFirstNonLocalhostInetAddress(); if (inetAddress == null) throw new MessageTransportException("Failed to set the Inet Address for this host. Is there a valid network interface?"); return new TcpDestination(inetAddress,port); } catch ( UnknownHostException e) { throw new MessageTransportException("Failed to identify the current hostname",e); } catch ( SocketException e) { throw new MessageTransportException("Failed to identify the current hostname",e); } }
Example 33
From project des, under directory /daemon/lib/apache-log4j-1.2.16/contribs/KitchingSimon/.
Source file: DatagramStringWriter.java

/** * This constructor sends messages to the specified host and port, and uses the specified character encoding when converting the message string to a byte sequence; the specified prefix (which may be null) is prepended to each message. */ public DatagramStringWriter(String host,int port,String encoding,String prefix){ this.host=host; this.port=port; this.encoding=encoding; this.prefix=prefix; try { this.address=InetAddress.getByName(host); } catch ( UnknownHostException e) { LogLog.error("Could not find " + host + ". All logging will FAIL.",e); } try { this.ds=new DatagramSocket(); } catch ( SocketException e) { e.printStackTrace(); LogLog.error("Could not instantiate DatagramSocket to " + host + ". All logging will FAIL.",e); } }
Example 34
private void openMulticastSocket(HostInfo hostInfo) throws IOException { if (_group == null) { _group=InetAddress.getByName(DNSConstants.MDNS_GROUP); } if (_socket != null) { this.closeMulticastSocket(); } _socket=new MulticastSocket(DNSConstants.MDNS_PORT); if ((hostInfo != null) && (hostInfo.getInterface() != null)) { try { _socket.setNetworkInterface(hostInfo.getInterface()); } catch ( SocketException e) { if (logger.isLoggable(Level.FINE)) { logger.fine("openMulticastSocket() Set network interface exception: " + e.getMessage()); } } } _socket.setTimeToLive(255); _socket.joinGroup(_group); }
Example 35
/** * ???????????????????? * @throws SocketException * @throws IOException */ public IPMessenger(){ this.userName="userName"; this.nickName="nickName"; this.group="group"; this.absenceMode=false; this.absenceMsg=""; try { this.hostName=InetAddress.getLocalHost().getHostName(); this.socket=new DatagramSocket(8899); } catch ( UnknownHostException e) { e.printStackTrace(); } catch ( SocketException e) { e.printStackTrace(); } this.in_port=8899; this.debug=true; }
Example 36
From project droidtv, under directory /src/com/chrulri/droidtv/.
Source file: StreamActivity.java

@Override protected void doInBackground(){ Log.d(TAG,">>>"); byte[] data=new byte[4096]; DatagramPacket dataPacket=new DatagramPacket(data,data.length); while (!isCancelled()) { Socket client; try { client=mHttpSocket.accept(); } catch ( IOException e) { continue; } try { OutputStream out=client.getOutputStream(); out.write(HTTP_HEADER.getBytes()); out.flush(); while (!isCancelled()) { try { mUdpSocket.receive(dataPacket); out.write(dataPacket.getData(),dataPacket.getOffset(),dataPacket.getLength()); } catch ( InterruptedIOException e) { Log.w(TAG,"udp timeout"); continue; } catch ( SocketException e) { break; } } } catch ( IOException e) { Log.e(TAG,"STREAM",e); } } Log.d(TAG,"<<<"); }
Example 37
From project dungbeetle, under directory /src/org/mobisocial/corral/.
Source file: ContentCorral.java

public void run(){ setName("AcceptThread"); Socket socket=null; while (true) { try { if (DBG) Log.d(TAG,"corral waiting for client..."); socket=mmServerSocket.accept(); if (DBG) Log.d(TAG,"corral client connected!"); } catch ( SocketException e) { Log.e(TAG,"accept() failed",e); break; } catch ( IOException e) { Log.e(TAG,"accept() failed",e); break; } if (socket == null) { break; } DuplexSocket duplex; try { duplex=new StreamDuplexSocket(socket.getInputStream(),socket.getOutputStream()); } catch ( IOException e) { Log.e(TAG,"Failed to connect to socket",e); return; } HttpConnectedThread conThread=new HttpConnectedThread(duplex); conThread.start(); } Log.d(TAG,"END mAcceptThread"); }
Example 38
From project eucalyptus, under directory /clc/modules/www/src/edu/ucsb/eucalyptus/admin/server/.
Source file: EucalyptusManagement.java

public static String getInternalIpAddress(){ String ipAddr=null; String localAddr="127.0.0.1"; List<NetworkInterface> ifaces=null; try { ifaces=Collections.list(NetworkInterface.getNetworkInterfaces()); } catch ( SocketException e1) { } for ( NetworkInterface iface : ifaces) try { if (!iface.isLoopback() && !iface.isVirtual() && iface.isUp()) { for ( InetAddress iaddr : Collections.list(iface.getInetAddresses())) { if (!iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) { ipAddr=iaddr.getHostAddress(); } else if (iaddr.isSiteLocalAddress() && !(iaddr instanceof Inet6Address)) { localAddr=iaddr.getHostAddress(); } } } } catch ( SocketException e1) { } return ipAddr == null ? localAddr : ipAddr; }
Example 39
public void start(){ try { Request request=makeRequest(); makeResponse(request); sendResponse(); } catch ( SocketException se) { } catch ( Throwable e) { e.printStackTrace(); } }
Example 40
From project flexmojos, under directory /flexmojos-testing/flexmojos-tester/src/main/java/net/flexmojos/oss/test/monitor/.
Source file: AbstractSocketThread.java

protected void openClientSocket() throws SocketException, IOException, SocketTimeoutException { clientSocket=serverSocket.accept(); getLogger().debug("[" + this.getClass().getName() + "] accepting data from client"); status=ThreadStatus.RUNNING; in=clientSocket.getInputStream(); out=clientSocket.getOutputStream(); }
Example 41
From project flume, under directory /flume-ng-core/src/main/java/org/apache/flume/instrumentation/.
Source file: GangliaServer.java

/** * Start this server, causing it to poll JMX at the configured frequency. */ @Override public void start(){ try { socket=new DatagramSocket(); hostname=InetAddress.getLocalHost().getHostName(); } catch ( SocketException ex) { logger.error("Could not create socket for metrics collection."); throw new FlumeException("Could not create socket for metrics collection.",ex); } catch ( Exception ex2) { logger.warn("Unknown error occured",ex2); } for ( HostInfo host : hosts) { addresses.add(new InetSocketAddress(host.getHostName(),host.getPortNumber())); } collectorRunnable.server=this; if (service.isShutdown() || service.isTerminated()) { service=Executors.newSingleThreadScheduledExecutor(); } service.scheduleWithFixedDelay(collectorRunnable,0,pollFrequency,TimeUnit.SECONDS); }
Example 42
From project Flume-Hive, under directory /src/java/com/cloudera/flume/reporter/ganglia/.
Source file: GangliaSink.java

@Override public void open() throws IOException { metricsServers=Util.parse(servers,DEFAULT_PORT); try { datagramSocket=new DatagramSocket(); } catch ( SocketException se) { LOG.warn("problem with ganglia socket",se); } }
Example 43
From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/master/.
Source file: FlumeMaster.java

/** * This returns true if the host running this process is in the list of master servers. The index is set in the FlumeConfiguration. If the host doesn't match, false is returned. If the hostnames in the master server list fail to resolve, an exception is thrown. */ public static boolean inferMasterHostID() throws UnknownHostException, SocketException { String masters=FlumeConfiguration.get().getMasterServers(); String[] mtrs=masters.split(","); int idx=NetUtils.findHostIndex(mtrs); if (idx < 0) { String localhost=NetUtils.localhost(); LOG.error("Attempted to start a master '{}' that is not " + "in the master servers list: '{}'",localhost,mtrs); return false; } FlumeConfiguration.get().setInt(FlumeConfiguration.MASTER_SERVER_ID,idx); LOG.info("Inferred master server index {}",idx); return true; }
Example 44
From project ftpserver-maven-plugin, under directory /src/test/java/cat/calidos/maven/ftpserver/.
Source file: FtpServerMojoTest.java

/** * Demo user should be able to login * @throws SocketException * @throws IOException */ public void testDemoUser() throws SocketException, IOException { ftp.login("demo","demo"); int reply=ftp.getReplyCode(); assertTrue(FTPReply.isPositiveCompletion(reply)); assertTrue("Can't login with demo user",ftp.isConnected()); String filename="test-file"; putFile(filename); boolean found=findRemoteItem(filename); assertTrue(filename + " can't be uploaded",found); ftp.disconnect(); }
Example 45
From project Gaggle, under directory /src/com/geeksville/location/.
Source file: SkyLinesTrackingWriter.java

/** * Constructor * @param key the SkyLines live tracking key * @throws Exception */ public SkyLinesTrackingWriter(long _key,int _intervalS) throws SocketException, UnknownHostException { key=_key; intervalMS=_intervalS * 1000; socket=new DatagramSocket(); InetAddress serverIP=InetAddress.getByName("78.47.50.46"); serverAddress=new InetSocketAddress(serverIP,5597); }
Example 46
From project gansenbang, under directory /s4/s4-core/src/main/java/io/s4/listener/.
Source file: CommLayerListener.java

public static String GetHostAddress() throws UnknownHostException, SocketException { Enumeration allNetInterfaces; InetAddress ip=null; allNetInterfaces=NetworkInterface.getNetworkInterfaces(); while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface=(NetworkInterface)allNetInterfaces.nextElement(); String niName=netInterface.getName(); if (!niName.equals("eth0") && !niName.equals("wlan0") && !niName.equals("br0")) continue; else { Enumeration addresses=netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip=(InetAddress)addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { break; } } } } return (ip != null ? ip.getHostAddress() : InetAddress.getLocalHost().getHostAddress()); }
Example 47
From project gecko, under directory /src/main/java/com/taobao/gecko/core/nio/impl/.
Source file: DatagramChannelController.java

protected void buildDatagramChannel() throws IOException, SocketException, ClosedChannelException { this.channel=DatagramChannel.open(); this.channel.socket().setSoTimeout(this.soTimeout); if (this.socketOptions.get(StandardSocketOption.SO_REUSEADDR) != null) { this.channel.socket().setReuseAddress(StandardSocketOption.SO_REUSEADDR.type().cast(this.socketOptions.get(StandardSocketOption.SO_REUSEADDR))); } if (this.socketOptions.get(StandardSocketOption.SO_RCVBUF) != null) { this.channel.socket().setReceiveBufferSize(StandardSocketOption.SO_RCVBUF.type().cast(this.socketOptions.get(StandardSocketOption.SO_RCVBUF))); } if (this.socketOptions.get(StandardSocketOption.SO_SNDBUF) != null) { this.channel.socket().setSendBufferSize(StandardSocketOption.SO_SNDBUF.type().cast(this.socketOptions.get(StandardSocketOption.SO_SNDBUF))); } this.channel.configureBlocking(false); if (this.localSocketAddress != null) { this.channel.socket().bind(this.localSocketAddress); } else { this.channel.socket().bind(new InetSocketAddress("localhost",0)); } this.setLocalSocketAddress((InetSocketAddress)this.channel.socket().getLocalSocketAddress()); }
Example 48
From project GeoBI, under directory /print/src/main/java/org/mapfish/print/config/.
Source file: AddressHostMatcher.java

protected byte[][] getAuthorizedIPs(InetAddress mask) throws UnknownHostException, SocketException { if (authorizedIPs == null) { InetAddress[] ips=InetAddress.getAllByName(ip); buildMaskedAuthorizedIPs(ips); } return authorizedIPs; }
Example 49
From project geronimo-javamail, under directory /geronimo-javamail_1.3.1/geronimo-javamail_1.3.1_provider/src/main/java/org/apache/geronimo/javamail/transport/smtp/.
Source file: SMTPTransport.java

/** * Receives one line from the server. A line is a sequence of bytes terminated by a CRLF * @return the line from the server as String */ protected String receiveLine(int delayMillis) throws MessagingException { if (socket == null || !socket.isConnected()) { throw new MessagingException("no connection"); } int timeout=0; try { timeout=socket.getSoTimeout(); socket.setSoTimeout(delayMillis); StringBuffer buff=new StringBuffer(); int c; boolean crFound=false, lfFound=false; while ((c=inputStream.read()) != -1 && crFound == false && lfFound == false) { if (c == CR) { crFound=true; } else if (c == LF) { lfFound=true; } else { buff.append((char)c); } } String line=buff.toString(); return line; } catch ( SocketException e) { throw new MessagingException(e.toString()); } catch ( IOException e) { throw new MessagingException(e.toString()); } finally { try { socket.setSoTimeout(timeout); } catch ( SocketException e) { } } }
Example 50
From project Gmote, under directory /gmoteclient/src/org/gmote/client/android/.
Source file: RemoteDesktop.java

public void run(){ DatagramSocket socket=null; try { socket=new DatagramSocket(); } catch ( SocketException e) { Log.e(DEBUG_TAG,e.getMessage(),e); } while (true) { sendTcpTileReq(); } }
Example 51
From project GraphWalker, under directory /src/main/java/org/graphwalker/.
Source file: Util.java

protected static InetAddress getInternetAddr(final String nic){ NetworkInterface iface=null; InetAddress ia=null; boolean foundNIC=false; try { for (Enumeration<NetworkInterface> ifaces=NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements() && foundNIC == false; ) { iface=ifaces.nextElement(); Util.logger.debug("Interface: " + iface.getDisplayName()); for (Enumeration<InetAddress> ips=iface.getInetAddresses(); ips.hasMoreElements() && foundNIC == false; ) { ia=ips.nextElement(); Util.logger.debug(ia.getCanonicalHostName() + " " + ia.getHostAddress()); if (!ia.isLoopbackAddress()) { Util.logger.debug(" Not a loopback address..."); if (!ia.getHostAddress().contains(":") && nic.equals(iface.getDisplayName())) { Util.logger.debug(" Host address does not contain ':'"); Util.logger.debug(" Interface: " + iface.getName() + " seems to be InternetInterface. I'll take it..."); foundNIC=true; } } } } } catch ( SocketException e) { Util.logger.error(e.getMessage()); } finally { if (!foundNIC && nic != null) { Util.logger.error("Could not bind to network interface: " + nic); throw new RuntimeException("Could not bind to network interface: " + nic); } else if (!foundNIC) { Util.logger.error("Could not bind to any network interface"); throw new RuntimeException("Could not bind to any network interface: "); } } return ia; }
Example 52
From project graylog2-server, under directory /src/main/java/org/graylog2/forwarders/forwarders/.
Source file: UDPForwarder.java

protected boolean send(byte[] what){ DatagramSocket sock=null; try { sock=new DatagramSocket(); InetAddress destination=InetAddress.getByName(this.getHost()); DatagramPacket pkg=new DatagramPacket(what,what.length,destination,this.getPort()); sock.send(pkg); } catch ( SocketException e) { LOG.error("Could not forward UDP syslog message: " + e.getMessage(),e); } catch ( UnknownHostException e) { LOG.warn("Could not forward UDP syslog message (Unknown host: <" + this.getHost() + ">): "+ e.getMessage(),e); } catch ( IOException e) { LOG.error("Could not forward UDP syslog message (IO error): " + e.getMessage(),e); } finally { if (sock != null) { sock.close(); } } return true; }
Example 53
From project grid-goggles, under directory /Dependent Libraries/oscP5/src/netP5/.
Source file: AbstractMulticast.java

private boolean openSocket(){ try { _myMulticastSocket=new MulticastSocket(); } catch ( SocketException e) { Logger.printError("Multicast.openSocket","cant create socket " + e.getMessage()); return false; } catch ( IOException e) { Logger.printError("Multicast.openSocket","cant create multicastSocket " + e.getMessage()); return false; } Logger.printProcess("Multicast.openSocket","multicast socket initialized."); return true; }
Example 54
From project groundhog-reader, under directory /src/main/java/com/almarsoft/GroundhogReader/lib/.
Source file: MessagePosterLib.java

public void postMessage() throws EncoderException, SocketException, IOException, ServerAuthException, UsenetReaderException { String headerText=createHeaderData(); String signature=getSignature(); ServerManager serverMgr=new ServerManager(mContext); mBody=MessageTextProcessor.shortenPostLines(mBody); Charset charset=CharsetUtil.getCharset(mPostCharset); ByteSequence bytebody=ContentUtil.encode(charset,mBody); mBody=new String(bytebody.toByteArray(),"ISO-8859-1"); try { mWakeLock.acquire(); serverMgr.postArticle(headerText,mBody,signature); } finally { if (mWakeLock.isHeld()) mWakeLock.release(); } if (mMyMsgId != null && mCurrentGroup != null) DBUtils.logSentMessage(mMyMsgId,mCurrentGroup,mContext); }
Example 55
From project hama, under directory /core/src/main/java/org/apache/hama/monitor/fd/.
Source file: UDPSupervisor.java

/** * UDP Supervisor. */ public UDPSupervisor(HamaConfiguration conf){ DatagramChannel ch=null; try { ch=DatagramChannel.open(); } catch ( IOException ioe) { LOG.error("Fail to open udp channel.",ioe); } this.channel=ch; if (null == this.channel) throw new NullPointerException("Channel can not be opened."); try { this.channel.socket().bind((SocketAddress)new InetSocketAddress(conf.getInt("bsp.monitor.fd.udp_port",16384))); } catch ( SocketException se) { LOG.error("Unable to bind the udp socket.",se); } WINDOW_SIZE.set(conf.getInt("bsp.monitor.fd.window_size",100)); this.receiver=Executors.newCachedThreadPool(); this.supervisor=Executors.newSingleThreadExecutor(); this.watcher=Executors.newSingleThreadScheduledExecutor(); }
Example 56
From project harmony, under directory /phosphorus-gmpls/src/main/java/org/opennaas/extensions/gmpls/utils/configuration_modules/gmre/.
Source file: GmreCli.java

/** * @param server * @param user * @param password * @param port * @throws GmreConnectionException */ public GmreCli(final String server,final String user,final String password,final int port) throws GmreConnectionException { try { logger.info("Connecting new GmreCli"); logger.debug("Server: " + server); logger.debug("Port: " + port); this.telnet.connect(server,port); this.in=this.telnet.getInputStream(); this.out=new PrintStream(this.telnet.getOutputStream()); this.readUntil("username[8chars]:"); this.write(user); this.readUntil("password[8chars]:"); this.write(password); this.readUntil(GmreCli.prompt + " "); } catch ( final SocketException e) { logger.warn("SocketException on: " + server + ":"+ port,e); throw new GmreConnectionException(e); } catch ( final IOException e) { logger.warn(e.getMessage(),e); throw new GmreConnectionException(e); } catch ( final InterruptedException e) { logger.warn(e.getMessage(),e); throw new GmreConnectionException(e); } }
Example 57
From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/haven/.
Source file: Session.java

public Session(InetAddress server,String username,byte[] cookie){ this.server=server; this.username=username; this.cookie=cookie; glob=new Glob(this); try { sk=new DatagramSocket(); } catch ( SocketException e) { throw (new RuntimeException(e)); } rworker=new RWorker(); rworker.start(); sworker=new SWorker(); sworker.start(); ticker=new Ticker(); ticker.start(); }
Example 58
From project hawtdispatch, under directory /hawtdispatch-transport/src/main/java/org/fusesource/hawtdispatch/transport/.
Source file: AbstractProtocolCodec.java

public void setTransport(Transport transport){ this.writeChannel=(GatheringByteChannel)transport.getWriteChannel(); this.readChannel=transport.getReadChannel(); if (nextDecodeAction == null) { nextDecodeAction=initialDecodeAction(); } if (transport instanceof TcpTransport) { TcpTransport tcp=(TcpTransport)transport; writeBufferSize=tcp.getSendBufferSize(); readBufferSize=tcp.getReceiveBufferSize(); } else if (transport instanceof UdpTransport) { UdpTransport tcp=(UdpTransport)transport; writeBufferSize=tcp.getSendBufferSize(); readBufferSize=tcp.getReceiveBufferSize(); } else { try { if (this.writeChannel instanceof SocketChannel) { writeBufferSize=((SocketChannel)this.writeChannel).socket().getSendBufferSize(); readBufferSize=((SocketChannel)this.readChannel).socket().getReceiveBufferSize(); } else if (this.writeChannel instanceof SslTransport.SSLChannel) { writeBufferSize=((SslTransport.SSLChannel)this.readChannel).socket().getSendBufferSize(); readBufferSize=((SslTransport.SSLChannel)this.writeChannel).socket().getReceiveBufferSize(); } } catch ( SocketException ignore) { } } if (bufferPools != null) { readBufferPool=bufferPools.getBufferPool(readBufferSize); writeBufferPool=bufferPools.getBufferPool(writeBufferSize); } }
Example 59
From project heritrix3, under directory /commons/src/main/java/org/apache/commons/httpclient/.
Source file: HttpConnection.java

/** * Set the {@link Socket}'s timeout, via {@link Socket#setSoTimeout}. If the connection is already open, the SO_TIMEOUT is changed. If no connection is open, then subsequent connections will use the timeout value. <p> Note: This is not a connection timeout but a timeout on network traffic! * @param timeout the timeout value * @throws SocketException - if there is an error in the underlyingprotocol, such as a TCP error. * @deprecated Use {@link HttpConnectionParams#setSoTimeout(int)}, {@link HttpConnection#getParams()}. */ public void setSoTimeout(int timeout) throws SocketException, IllegalStateException { this.params.setSoTimeout(timeout); if (this.socket != null) { this.socket.setSoTimeout(timeout); } }
Example 60
From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/datacollection/controller/.
Source file: ChukwaAgentController.java

/** * Registers this {@link Adaptor} with the agent running at the specifiedhostname and portno * @return The id of the this {@link Adaptor}, assigned by the agent upon successful registration * @throws IOException */ String register() throws IOException { Socket s=new Socket(hostname,portno); try { s.setSoTimeout(60000); } catch ( SocketException e) { log.warn("Error while settin soTimeout to 60000"); e.printStackTrace(); } PrintWriter bw=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); if (id != null) bw.println("ADD " + id + " = "+ className+ " "+ appType+ " "+ params+ " "+ offset); else bw.println("ADD " + className + " "+ appType+ " "+ params+ " "+ offset); bw.flush(); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String resp=br.readLine(); if (resp != null) { String[] fields=resp.split(" "); if (fields[0].equals("OK")) { id=fields[fields.length - 1]; } } s.close(); return id; }
Example 61
protected void newReceiver(){ if (receiver != null) { receiver.stopListening(); receiver.close(); } try { try { receiver=new OSCPortIn(in); } catch ( BindException be) { int oldIn=in; in++; Ut.alert("Port already in use","Port n" + oldIn + " is already in use, setting it to : "+ in); receiver=new OSCPortIn(in); } } catch ( SocketException e) { Ut.alert("Error : SocketException","Problem while creating an input connection,\nTransport won't be available.\nplease see the console\n(Application/Utilities/Console.app)\nfor more informations."); e.printStackTrace(); open=false; receiver=null; Ut.barMenu.update(); } if (receiver != null) { receiver.addListener(keyIn,this); receiver.startListening(); } }
Example 62
From project hs4j, under directory /src/main/java/com/google/code/hs4j/network/nio/.
Source file: TCPController.java

/** * @param sk * @param sc * @throws IOException * @throws SocketException */ private void closeAcceptChannel(SelectionKey sk,SocketChannel sc) throws IOException, SocketException { if (sk != null) { sk.cancel(); } if (sc != null) { sc.socket().setSoLinger(true,0); sc.socket().shutdownOutput(); sc.close(); } }
Example 63
From project httpcache4j, under directory /httpcache4j-core/src/main/java/org/codehaus/httpcache4j/cache/.
Source file: HTTPCacheHelper.java

Headers warn(Headers headers,IOException e){ headers=headers.add(Warning.STALE_WARNING.toHeader()); if (e instanceof SocketException) { headers=headers.add(Warning.DISCONNECT_OPERATION_WARNING.toHeader()); } return headers; }
Example 64
From project httpClient, under directory /httpclient/src/main/java/org/apache/http/conn/.
Source file: BasicManagedEntity.java

public boolean streamClosed(InputStream wrapped) throws IOException { try { if (attemptReuse && (managedConn != null)) { boolean valid=managedConn.isOpen(); try { wrapped.close(); managedConn.markReusable(); } catch ( SocketException ex) { if (valid) { throw ex; } } } } finally { releaseManagedConnection(); } return false; }
Example 65
From project httpcore, under directory /httpcore/src/main/java/org/apache/http/impl/.
Source file: BHttpConnectionBase.java

public void setSocketTimeout(int timeout){ assertOpen(); if (this.socket != null) { try { this.socket.setSoTimeout(timeout); } catch ( SocketException ignore) { } } }
Example 66
From project ib-ruby, under directory /misc/IBController 2-9-0/src/ibcontroller/.
Source file: CommandChannel.java

void close(){ try { mSocket.shutdownInput(); mSocket.shutdownOutput(); mInstream.close(); mInstream=null; mOutstream.close(); mOutstream=null; mSocket.close(); mSocket=null; } catch ( SocketException e) { } catch ( IOException e) { } }
Example 67
From project iJetty, under directory /console/webapp/src/main/java/org/mortbay/ijetty/console/.
Source file: IPServlet.java

protected void doContent(PrintWriter writer,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { writer.println("<h1 class='pageheader'>Network Interfaces Reported by Android</h1><div id='content'>"); try { writer.println("<table cellspacing='0' cellpadding='2' border='1'>"); writer.println("<thead><th>Interface</th><th>IP</th></thead>"); writer.println("<tbody>"); Enumeration<NetworkInterface> nis=NetworkInterface.getNetworkInterfaces(); for ( NetworkInterface ni : Collections.list(nis)) { writer.println("<tr>"); writer.printf("<td valign='top'>%s</td>%n",ni.getDisplayName()); writer.println("<td>"); Enumeration<InetAddress> iis=ni.getInetAddresses(); for ( InetAddress ia : Collections.list(iis)) { writer.printf("<p class='singleline'>%s</p>",ia.getHostAddress()); } writer.println("</td>"); writer.println("</tr>"); } writer.println("</tbody>"); writer.println("</table>"); } catch ( SocketException e) { writer.println("Socket Exception: No Network Interfaces Available?"); } writer.println("</div>"); }
Example 68
From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/udp/.
Source file: UDPEmitter.java

@Inject public UDPEmitter(Cluster topology){ this.topology=topology; nodes=HashBiMap.create(topology.getPhysicalCluster().getNodes().size()); for ( ClusterNode node : topology.getPhysicalCluster().getNodes()) { nodes.forcePut(node.getPartition(),node); } try { socket=new DatagramSocket(); } catch ( SocketException se) { throw new RuntimeException(se); } }
Example 69
private void openMulticastSocket(HostInfo hostInfo) throws IOException { if (_group == null) { if (hostInfo.getInetAddress() instanceof Inet6Address) { _group=InetAddress.getByName(DNSConstants.MDNS_GROUP_IPV6); } else { _group=InetAddress.getByName(DNSConstants.MDNS_GROUP); } } if (_socket != null) { this.closeMulticastSocket(); } _socket=new MulticastSocket(DNSConstants.MDNS_PORT); if ((hostInfo != null) && (hostInfo.getInterface() != null)) { try { _socket.setNetworkInterface(hostInfo.getInterface()); } catch ( SocketException e) { if (logger.isLoggable(Level.FINE)) { logger.fine("openMulticastSocket() Set network interface exception: " + e.getMessage()); } } } _socket.setTimeToLive(255); _socket.joinGroup(_group); }
Example 70
From project jagger, under directory /chassis/coordinator.http/src/main/java/com/griddynamics/jagger/coordinator/http/client/.
Source file: ExchangeClient.java

public PackResponse exchange() throws Throwable { log.debug("Exchange requested from agent {}",nodeContext.getId()); Pack out=packExchanger.retrieve(); log.debug("Going to send pack {} from agent {}",out,nodeContext.getId()); PackRequest request=PackRequest.create(nodeContext.getId(),out); PackResponse packResponse=null; String str=null; try { str=exchangeData(urlExchangePack,request); packResponse=SerializationUtils.fromString(str); log.debug("Pack response {} from agent {}",packResponse,nodeContext.getId()); if (Ack.FAIL.equals(packResponse.getAck())) { log.warn("Pack retrieving failed! Agent {}",nodeContext.getId()); throw packResponse.getError(); } Pack in=packResponse.getPack(); packExchanger.process(in); } catch ( SocketException e) { packExchanger.getCommandsToSend().addAll(out.getCommands()); packExchanger.getResultsToSend().addAll(out.getResults()); log.warn("Connection lost! Pack {} will be sent again in the next exchange session!",out); } catch ( IOException e) { log.error("IOException during deserialization of this data ({})",str); throw e; } return packResponse; }
Example 71
private void openMulticastSocket(HostInfo hostInfo) throws IOException { if (_group == null) { _group=InetAddress.getByName(DNSConstants.MDNS_GROUP); } if (_socket != null) { this.closeMulticastSocket(); } _socket=new MulticastSocket(DNSConstants.MDNS_PORT); if ((hostInfo != null) && (hostInfo.getInterface() != null)) { try { _socket.setNetworkInterface(hostInfo.getInterface()); } catch ( SocketException e) { if (logger.isLoggable(Level.FINE)) { logger.fine("openMulticastSocket() Set network interface exception: " + e.getMessage()); } } } _socket.setTimeToLive(255); _socket.joinGroup(_group); }
Example 72
From project jamod, under directory /src/main/java/net/wimpi/modbus/io/.
Source file: ModbusTCPTransport.java

public ModbusRequest readRequest() throws ModbusIOException { try { ModbusRequest req=null; synchronized (m_ByteIn) { byte[] buffer=m_ByteIn.getBuffer(); if (m_Input.read(buffer,0,6) == -1) { throw new EOFException("Premature end of stream (Header truncated)."); } int bf=ModbusUtil.registerToShort(buffer,4); if (m_Input.read(buffer,6,bf) == -1) { throw new ModbusIOException("Premature end of stream (Message truncated)."); } m_ByteIn.reset(buffer,(6 + bf)); m_ByteIn.skip(7); int functionCode=m_ByteIn.readUnsignedByte(); m_ByteIn.reset(); req=ModbusRequest.createModbusRequest(functionCode); req.readFrom(m_ByteIn); } return req; } catch ( EOFException eoex) { throw new ModbusIOException(true); } catch ( SocketException sockex) { throw new ModbusIOException(true); } catch ( Exception ex) { ex.printStackTrace(); throw new ModbusIOException("I/O exception - failed to read."); } }
Example 73
From project JavaJunction, under directory /src/main/java/edu/stanford/junction/provider/jx/.
Source file: JunctionProvider.java

public static String getLocalIpAddress(){ try { for (Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf=en.nextElement(); for (Enumeration<InetAddress> enumIpAddr=intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress=enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { if (!inetAddress.getHostAddress().contains(":")) { return inetAddress.getHostAddress().toString(); } } } } } catch ( SocketException ex) { Log.e("junction",ex.toString()); } return null; }
Example 74
From project JavaOSC, under directory /modules/core/src/main/java/com/illposed/osc/.
Source file: OSCPortIn.java

/** * Run the loop that listens for OSC on a socket until * @{link #isListening()} becomes false. * @see java.lang.Runnable#run() */ public void run(){ byte[] buffer=new byte[BUFFER_SIZE]; DatagramPacket packet=new DatagramPacket(buffer,BUFFER_SIZE); DatagramSocket socket=getSocket(); while (listening) { try { try { socket.receive(packet); } catch ( SocketException ex) { if (listening) { throw ex; } else { continue; } } OSCPacket oscPacket=converter.convert(buffer,packet.getLength()); dispatcher.dispatchPacket(oscPacket); } catch ( IOException e) { e.printStackTrace(); } } }
Example 75
From project jboss-ejb-client, under directory /src/main/java/org/jboss/ejb/client/remoting/.
Source file: ClusterNode.java

/** * Returns all the {@link InetAddress}es that are applicable for the current system. This is done by fetching all the {@link NetworkInterface network interfaces} and then getting the {@link InetAddress}es for each of the network interface. * @return * @throws SocketException */ private static Collection<InetAddress> getAllApplicableInetAddresses() throws SocketException { final Collection<InetAddress> addresses=new HashSet<InetAddress>(); final Enumeration<NetworkInterface> networkInterfaces=NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { final NetworkInterface networkInterface=networkInterfaces.nextElement(); final Enumeration<InetAddress> inetAddresses=networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { addresses.add(inetAddresses.nextElement()); } } return addresses; }
Example 76
From project jclouds-chef, under directory /core/src/test/java/org/jclouds/ohai/config/.
Source file: OhaiModuleTest.java

@Test public void test() throws SocketException { final Properties sysProperties=new Properties(); sysProperties.setProperty("os.name","Mac OS X"); sysProperties.setProperty("os.version","10.3.0"); sysProperties.setProperty("user.name","user"); Injector injector=Guice.createInjector(new AbstractModule(){ @Override protected void configure(){ bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefAsyncApi.VERSION); } } ,new ChefParserModule(),new GsonModule(),new OhaiModule(){ @Override protected Long millis(){ return 127999291932529l; } @Override protected Properties systemProperties(){ return sysProperties; } } ); Ohai ohai=injector.getInstance(Ohai.class); Json json=injector.getInstance(Json.class); assertEquals(json.toJson(ohai.ohai.get(),new TypeLiteral<Map<String,JsonBall>>(){ } .getType()),"{\"ohai_time\":127999291932529,\"platform\":\"macosx\",\"platform_version\":\"10.3.0\",\"current_user\":\"user\",\"jvm\":{\"system\":{\"user.name\":\"user\",\"os.version\":\"10.3.0\",\"os.name\":\"Mac OS X\"}}}"); }
Example 77
From project jcollectd, under directory /src/main/java/org/collectd/protocol/.
Source file: UdpReceiver.java

public void listen(DatagramSocket socket) throws IOException { while (true) { byte[] buf=new byte[Network.BUFFER_SIZE]; DatagramPacket packet=new DatagramPacket(buf,buf.length); try { socket.receive(packet); } catch ( SocketException e) { if (_isShutdown) { break; } else { throw e; } } parse(packet.getData()); } }
Example 78
From project jcr-openofficeplugin, under directory /src/main/java/org/exoplatform/applications/ooplugin/client/.
Source file: HttpClient.java

public void conect() throws Exception { for (int i=0; i < 10; i++) { try { clientSocket=new Socket(server,port); outStream=clientSocket.getOutputStream(); outPrintStream=new PrintStream(clientSocket.getOutputStream()); inputStream=clientSocket.getInputStream(); return; } catch ( SocketException exc) { Thread.sleep(500); } } }
Example 79
From project jdcbot, under directory /src/org/elite/jdcbot/framework/.
Source file: InputThread.java

public void run(){ try { running=true; while (running) { String rawCommand=null; rawCommand=this.ReadCommand(_in); if ((rawCommand == null) || (rawCommand.length() == 0)) { running=false; _inputThreadTrgt.disconnected(); } else _inputThreadTrgt.handleCommand(rawCommand); onReadingCommand(); } } catch ( Exception e) { if (!(e instanceof SocketException && e.getMessage().equals("Socket closed"))) logger.error("Exception in run()",e); _inputThreadTrgt.disconnected(); } logger.info("Input thread now terminated."); }
Example 80
From project jetty-project, under directory /jetty-integration-tests/src/test/java/org/mortbay/jetty/integration/ssl/.
Source file: SSLContextTest.java

/** * This runs the main test: it runs a client and a server. * @param sslClientContext SSLContext to be used by the client. * @return true if the server accepted the SSL certificate. * @throws IOException */ public boolean runSSLContextTest(SSLContext sslClientContext,Connector connector) throws Exception { boolean result=false; Server server=new Server(); server.setConnectors(new Connector[]{connector}); server.setHandler(new HelloWorldHandler()); server.start(); int testPort=connector.getLocalPort(); SSLSocket sslClientSocket=null; try { SSLSocketFactory sslClientSocketFactory=sslClientContext.getSocketFactory(); sslClientSocket=(SSLSocket)sslClientSocketFactory.createSocket("localhost",testPort); assertTrue("Client socket connected",sslClientSocket.isConnected()); sslClientSocket.setSoTimeout(500); OutputStream os=sslClientSocket.getOutputStream(); os.write(REQUEST0.getBytes()); os.write(REQUEST0.getBytes()); os.flush(); os.write(REQUEST1.getBytes()); os.flush(); String responses=readResponse(sslClientSocket); assertEquals(RESPONSE0 + RESPONSE0 + RESPONSE1,responses); result=true; } catch ( SocketException e) { result=false; } catch ( SSLHandshakeException e) { result=false; printSslException("! Client: ",e,sslClientSocket); } finally { server.stop(); } return result; }
Example 81
/** * Creates a new server thread object on the specified {@link Socket}. * @param name thread name. * @param socket socket to talk with. * @param timeout socket timeout. * @throws SocketException if a socket error occurs. */ public Server(final String name,final Socket socket,final int timeout) throws SocketException { super(name); this.socket=socket; socket.setSoTimeout(timeout); socket.setTcpNoDelay(true); }
Example 82
From project jnrpe-lib, under directory /jnrpe-lib/src/main/java/it/jnrpe/.
Source file: JNRPEListenerThread.java

/** * Executes the thread. */ public void run(){ try { init(); EventsUtil.sendEvent(m_vEventListeners,this,LogEvent.INFO,"Listening on " + m_sBindingAddress + ":"+ m_iBindingPort); while (true) { Socket clientSocket=m_serverSocket.accept(); if (!canAccept(clientSocket.getInetAddress())) { clientSocket.close(); continue; } JNRPEServerThread kk=m_threadFactory.createNewThread(clientSocket); kk.configure(this,m_vEventListeners); kk.start(); } } catch ( SocketException se) { } catch ( Exception e) { EventsUtil.sendEvent(m_vEventListeners,this,LogEvent.ERROR,e.getMessage(),e); } exit(); }
Example 83
From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/channel/.
Source file: BASE24Channel.java

/** * @return a byte array with the received message * @exception IOException */ protected byte[] streamReceive() throws IOException { int i; byte[] buf=new byte[4096]; for (i=0; i < 4096; i++) { int c=-1; try { c=serverIn.read(); } catch ( SocketException e) { } if (c == 03) break; else if (c == -1) throw new EOFException("connection closed"); buf[i]=(byte)c; } if (i == 4096) throw new IOException("packet too long"); byte[] d=new byte[i]; System.arraycopy(buf,0,d,0,i); return d; }
Example 84
From project jredis, under directory /core/ri/src/main/java/org/jredis/ri/alphazero/protocol/.
Source file: ProtocolBase.java

/** * Writes the entire content of the message to the output stream and flushes it. * @param out the stream to write the Request message to. */ @Override public void write(OutputStream out) throws ClientRuntimeException, ProviderException { try { buffer.writeTo(out); out.flush(); } catch ( SocketException e) { Log.error("StreamBufferRequest.write(): SocketException on write: " + e.getLocalizedMessage()); throw new ClientRuntimeException("socket exception",e); } catch ( IOException e) { Log.error("StreamBufferRequest.write(): IOException on write: " + e.getLocalizedMessage()); throw new ClientRuntimeException("stream io exception",e); } }
Example 85
From project JsTestDriver, under directory /idea-plugin/src/com/google/jstestdriver/idea/.
Source file: TestRunner.java

private static Socket connectToServer(int port) throws IOException { int retries=RETRIES; Socket socket=null; do { try { socket=new Socket(); socket.connect(new InetSocketAddress(getLocalHost(),port),TIMEOUT_MILLIS); break; } catch ( SocketException e) { retries--; } } while (retries > 0); return socket; }
Example 86
From project jtrek, under directory /src/org/gamehost/jtrek/javatrek/.
Source file: TrekMonitorClient.java

protected synchronized void sendOutputBuffer(){ try { if (!outputBuffer.equals("")) { outputBuffer=outputBuffer.replace('\010','\000'); Timer timeToDie=new Timer("MonitorClient-" + monPlayer); timeToDie.schedule(new TrekDeadThreadKiller(this),1000); out.write(outputBuffer.getBytes()); out.flush(); timeToDie.cancel(); } } catch ( java.net.SocketException se) { TrekLog.logError(se.getMessage()); kill(); } catch ( Exception e) { TrekLog.logException(e); kill(); } finally { outputBuffer=""; } }
Example 87
protected void setReadTimeout(int millis) throws SocketException { Socket sock=mSocket; if (sock != null) { sock.setSoTimeout(millis); } }
Example 88
From project kelpie, under directory /src/main/java/com/voxbone/kelpie/.
Source file: RtpRelay.java

private DatagramChannel makeDatagramChannel(boolean any) throws IOException { DatagramChannel socket=DatagramChannel.open(); while (!socket.socket().isBound()) { nextPort+=1; if (nextPort > RTP_MAX_PORT) { nextPort=RTP_MIN_PORT; } logger.debug("[[" + cs.internalCallId + "]] trying to bind to port: "+ nextPort); try { if (!any) { socket.socket().bind(new InetSocketAddress(SipService.getLocalIP(),nextPort)); } else { socket.socket().bind(new InetSocketAddress(nextPort)); } } catch ( SocketException e) { logger.error("Unable to make RTP socket!",e); } } return socket; }
Example 89
From project kevoree-library, under directory /kalimucho/org.kevoree.library.kalimucho.kalimuchoNode/src/main/java/network/connectors/ip/.
Source file: IPConnectorACKSender.java

/** * Send ans acknowledge message for a connector on IP */ public void sendACK(){ int compteEssaiRestants=3; while (compteEssaiRestants != 0) { try { ecrire.reset(); ecrire.writeObject(nomConnecteur + ";" + myID); ecrire.flush(); compteEssaiRestants=0; } catch ( SocketException se) { try { KalimuchoDNS dns=(KalimuchoDNS)ServicesRegisterManager.lookForService(Parameters.KALIMUCHO_DNS_MANAGER); dns.removeReference(new NetworkAddress(pourAck.getInetAddress().getHostAddress())); } catch ( ServiceClosedException sce) { } compteEssaiRestants=0; } catch ( InvalidClassException ice) { compteEssaiRestants=0; gestionnaireContexte.signalEvent(new ContextInformation(nomConnecteur + " error when sending IP ACK message: invalid class")); } catch ( NotSerializableException ice) { compteEssaiRestants=0; gestionnaireContexte.signalEvent(new ContextInformation(nomConnecteur + " error when sending IP ACK message: not serializable class")); } catch ( IOException e) { compteEssaiRestants--; if (compteEssaiRestants == 0) { try { KalimuchoDNS dns=(KalimuchoDNS)ServicesRegisterManager.lookForService(Parameters.KALIMUCHO_DNS_MANAGER); dns.removeReference(new NetworkAddress(pourAck.getInetAddress().getHostAddress())); } catch ( ServiceClosedException sce) { } gestionnaireContexte.signalEvent(new ContextInformation(nomConnecteur + " error when sending IP ACK message: IO")); } } } }