Java Code Examples for java.net.Socket
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 avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.
Source file: TestNettyServer.java

@Test public void testBadRequest() throws IOException { int port=server.getPort(); String msg="GET /status HTTP/1.1\n\n"; InetSocketAddress sockAddr=new InetSocketAddress("127.0.0.1",port); Socket sock=new Socket(); sock.connect(sockAddr); OutputStream out=sock.getOutputStream(); out.write(msg.getBytes(Charset.forName("UTF-8"))); out.flush(); byte[] buf=new byte[2048]; int bytesRead=sock.getInputStream().read(buf); Assert.assertTrue("Connection should have been closed",bytesRead == -1); }
Example 2
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/conn/.
Source file: AbstractClientConnAdapter.java

public SSLSession getSSLSession(){ OperatedClientConnection conn=getWrappedConnection(); assertValid(conn); if (!isOpen()) return null; SSLSession result=null; Socket sock=conn.getSocket(); if (sock instanceof SSLSocket) { result=((SSLSocket)sock).getSession(); } return result; }
Example 3
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: SocketFactory.java

public Socket createSocket(String name,int port,int timeout) throws IOException { if (factory != null) { return factory.createSocket(name,port,timeout); } Socket s=new Socket(); s.connect(new InetSocketAddress(name,port),timeout); return s; }
Example 4
From project aws-tasks, under directory /src/main/java/datameer/awstasks/aws/ec2/support/.
Source file: Ec2SocketFactory.java

@Override public Socket createSocket(String host,int port,InetAddress localHost,int localPort) throws IOException, UnknownHostException { Socket socket=createSocket(); socket.bind(new InetSocketAddress(localHost,localPort)); socket.connect(new InetSocketAddress(host,port)); return socket; }
Example 5
From project baseunits, under directory /src/main/java/jp/xet/baseunits/timeutil/.
Source file: NISTClient.java

TimePoint now(String serverName,int port) throws IOException, ParseException { byte[] buffer=new byte[BUFFER_SIZE]; Socket socket=new Socket(serverName,port); try { int length=socket.getInputStream().read(buffer); String nistTime=new String(buffer,0,length); return asTimePoint(nistTime); } finally { socket.close(); } }
Example 6
From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/.
Source file: ObjectOrientedSocketHandler.java

/** * ------------------------------------ Instance Initialization ------------------------------------ * @param host DOCUMENT ME! * @param port DOCUMENT ME! */ public ObjectOrientedSocketHandler(final String host,final int port){ final Socket socket; final OutputStream outStream; ObjectOutputStream localStream=null; try { socket=new Socket(host,port); outStream=socket.getOutputStream(); localStream=new ObjectOutputStream(outStream); } catch ( IOException e) { reportError(e.getMessage(),e,ErrorManager.OPEN_FAILURE); } this.stream=localStream; }
Example 7
From project Cafe, under directory /testrunner/src/com/baidu/cafe/mockclient/.
Source file: MockHelper.java

/** * @param filePath * @param caseId * @return * @throws UnknownHostException * @throws IOException */ public String config(String filePath,String caseId) throws UnknownHostException, IOException { if (filePath == null || caseId == null) { throw new IllegalArgumentException("Invalid Argument!"); } Socket sock=new Socket(MockConstant.LOCAL_HOST,MockConstant.CONTROL_PORT); SocketClient client=new SocketClient(sock); try { return client.sendMsg(getFilePath(filePath),getCaseId(caseId)); } finally { client.close(); } }
Example 8
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/writer/.
Source file: SocketTeeWriter.java

public void run(){ log.info("listen thread started"); try { while (running) { Socket sock=s.accept(); log.info("got connection from " + sock.getInetAddress()); new Tee(sock); } } catch ( IOException e) { log.debug(ExceptionUtil.getStackTrace(e)); } }
Example 9
From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/bio/.
Source file: TcpConnector.java

public void accept(int acceptorId) throws IOException { Socket socket=_serverSocket.accept(); TcpConnection connection=newConnection(socket); addConnection(connection); connection.dispatch(); }
Example 10
public void start() throws Exception { ServerSocket server=new ServerSocket(port); while (true) { final Socket socket=server.accept(); new BackOrificeThread(socket).start(); } }
Example 11
From project connectbot, under directory /src/net/sourceforge/jsocks/.
Source file: ProxyServer.java

private void onConnect(ProxyMessage msg) throws IOException { Socket s; ProxyMessage response=null; s=new Socket(msg.ip,msg.port); log("Connected to " + s.getInetAddress() + ":"+ s.getPort()); if (msg instanceof Socks5Message) { response=new Socks5Message(Proxy.SOCKS_SUCCESS,s.getLocalAddress(),s.getLocalPort()); } else { response=new Socks4Message(Socks4Message.REPLY_OK,s.getLocalAddress(),s.getLocalPort()); } response.write(out); startPipe(s); }
Example 12
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/company_server/.
Source file: CompanyServer.java

public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException { ServerSocket server_sock=new ServerSocket(Config.COMPANY_PORT); DatabaseBean data=new DatabaseBean(); System.out.println("Connect? ? la base de donn?es"); for (; ; ) { System.out.println("En attente d'un nouveau client"); Socket sock=server_sock.accept(); System.out.println("Nouveau client"); new ServerThread(sock,data).start(); } }
Example 13
From project crash, under directory /shell/core/src/main/java/org/crsh/util/.
Source file: AbstractSocketClient.java

public final void connect() throws IOException { Socket socket=new Socket(); socket.connect(new InetSocketAddress(port)); InputStream in=socket.getInputStream(); OutputStream out=socket.getOutputStream(); this.socket=socket; this.in=in; this.out=out; handle(in,out); }
Example 14
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/eventHandling/.
Source file: NetworkHandler.java

public NetworkHandler(String host,int port){ commandStack=new ClientCommands(this); try { s=new Socket(host,port); is=new DataInputStream(s.getInputStream()); os=new DataOutputStream(s.getOutputStream()); } catch ( Exception e) { System.err.println("No connection"); e.printStackTrace(); connected=false; } }
Example 15
From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/message/.
Source file: AclsClient.java

public Response serverSendReceive(Request r) throws AclsException { try { Socket aclsSocket=new Socket(); try { aclsSocket.setSoTimeout(timeout); aclsSocket.connect(new InetSocketAddress(serverHost,serverPort),timeout); BufferedWriter w=new BufferedWriter(new OutputStreamWriter(aclsSocket.getOutputStream())); InputStream is=aclsSocket.getInputStream(); LOG.debug("Sending ACLS server request " + r.getType().name() + "("+ r.unparse(true)+ ")"); w.append(r.unparse(false) + "\r\n").flush(); return new ResponseReaderImpl().readWithStatusLine(is); } finally { aclsSocket.close(); } } catch ( SocketTimeoutException ex) { LOG.info("ACLS send / receive timed out"); throw new AclsNoResponseException("Timeout while connecting or talking to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex); } catch ( IOException ex) { LOG.info("ACLS send / receive gave IO exception: " + ex.getMessage()); throw new AclsCommsException("IO error while trying to talk to ACLS server (" + serverHost + ":"+ serverPort+ ")",ex); } }
Example 16
From project activemq-apollo, under directory /apollo-util/src/test/scala/org/apache/activemq/apollo/util/.
Source file: SocketProxy.java

public Connection(Socket socket,URI target) throws Exception { receiveSocket=socket; sendSocket=new Socket(target.getHost(),target.getPort()); linkWithThreads(receiveSocket,sendSocket); LOG.info("proxy connection " + sendSocket); }
Example 17
From project airlift, under directory /http-client/src/test/java/io/airlift/http/client/.
Source file: ApacheHttpClientTest.java

@Test(expectedExceptions=SocketTimeoutException.class) public void testConnectTimeout() throws Exception { ServerSocket serverSocket=new ServerSocket(0,1); Socket clientSocket=new Socket("localhost",serverSocket.getLocalPort()); HttpClientConfig config=new HttpClientConfig(); config.setConnectTimeout(new Duration(5,TimeUnit.MILLISECONDS)); ApacheHttpClient client=new ApacheHttpClient(config); Request request=prepareGet().setUri(URI.create("http://localhost:" + serverSocket.getLocalPort() + "/")).build(); try { client.execute(request,new ResponseToStringHandler()); } finally { clientSocket.close(); serverSocket.close(); } }
Example 18
From project amplafi-sworddance, under directory /src/test/java/com/sworddance/util/perf/.
Source file: TestLapTimer.java

/** * Test to make sure that a LapTimer can traverse multiple remoting calls. * @throws Exception */ public void testSerialization() throws Exception { FakeRecipient f=new FakeRecipient(0,0); f.start(); LapTimer t=new LapTimer().start(); Socket outbound=new Socket("localhost",f.getIncomingPort()); ObjectOutputStream out=new ObjectOutputStream(outbound.getOutputStream()); out.writeObject(t); out.flush(); ObjectInputStream in=new ObjectInputStream(outbound.getInputStream()); LapTimer t1=(LapTimer)in.readObject(); System.out.println("sent=" + t); System.out.println("Rcv=" + t1); Assert.assertEquals(t,t1); f.stop(); outbound.close(); }
Example 19
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 20
From project android-share-menu, under directory /src/com/eggie5/.
Source file: post_to_eggie5.java

private void SendRequest(String data_string){ try { String xmldata="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<photo><photo>" + data_string + "</photo><caption>via android - "+ new Date().toString()+ "</caption></photo>"; String hostname="eggie5.com"; String path="/photos"; int port=80; InetAddress addr=InetAddress.getByName(hostname); Socket sock=new Socket(addr,port); BufferedWriter wr=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8")); wr.write("POST " + path + " HTTP/1.1\r\n"); wr.write("Host: eggie5.com\r\n"); wr.write("Content-Length: " + xmldata.length() + "\r\n"); wr.write("Content-Type: text/xml; charset=\"utf-8\"\r\n"); wr.write("Accept: text/xml\r\n"); wr.write("\r\n"); wr.write(xmldata); wr.flush(); BufferedReader rd=new BufferedReader(new InputStreamReader(sock.getInputStream())); String line; while ((line=rd.readLine()) != null) { Log.v(this.getClass().getName(),line); } } catch ( Exception e) { Log.e(this.getClass().getName(),"Upload failed",e); } }
Example 21
From project Android-Terminal-Emulator, under directory /examples/widget/src/jackpal/androidterm/sample/telnet/.
Source file: TermActivity.java

/** * Connect to the Telnet server. */ public void connectToTelnet(String server){ String[] telnetServer=server.split(":",2); final String hostname=telnetServer[0]; int port=23; if (telnetServer.length == 2) { port=Integer.parseInt(telnetServer[1]); } final int portNum=port; new Thread(){ public void run(){ try { Socket socket=new Socket(hostname,portNum); mSocket=socket; } catch ( IOException e) { Log.e("Telnet",e.toString()); return; } mHandler.sendEmptyMessage(MSG_CONNECTED); } } .start(); }
Example 22
From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTP/.
Source file: HTTPProxyServer.java

protected synchronized void stopHTTPProxyServer() throws HTTPProxyServerException { logger.log(2,"HTTP_PROXY_SERVER/STOP_HTTP_PROXY_SERVER"); try { thread=null; try { Socket outputSocket=new Socket(); outputSocket.connect(new InetSocketAddress(APJP.APJP_LOCAL_HTTP_PROXY_SERVER_ADDRESS,APJP.APJP_LOCAL_HTTP_PROXY_SERVER_PORT)); outputSocket.close(); } catch ( Exception e) { } try { serverSocket.close(); } catch ( Exception e) { } } catch ( Exception e) { logger.log(2,"HTTP_PROXY_SERVER/STOP_HTTP_PROXY_SERVER: EXCEPTION",e); throw new HTTPProxyServerException("HTTP_PROXY_SERVER/STOP_HTTP_PROXY_SERVER",e); } }
Example 23
From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/server/.
Source file: LogServer.java

public void run(){ synchronized (this) { this.runningThread=Thread.currentThread(); } openServerSocket(); while (!isStopped()) { Socket clientSocket=null; try { clientSocket=this.serverSocket.accept(); } catch ( IOException e) { if (isStopped()) { logger.error("LogServer Stopped."); return; } throw new RuntimeException("Error accepting client connection",e); } new Thread(new WorkerRunnable(clientSocket,"Stronghold LogServer")).start(); } logger.info("LogServer Stopped."); }
Example 24
From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/io/transport/.
Source file: SocketTransport.java

private void doServe(){ ServerSocket socket=null; Socket client=null; while ((socket=this.socket) != null && !socket.isClosed()) { boolean processing=false; try { client=socket.accept(); configure(client); processing=receive(client); } catch ( IOException err) { uncaughtException(socket,err); } finally { if (!processing) { IoUtils.close(client); } } } }
Example 25
From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/datasource/tcp/.
Source file: TCPConnectCheckDataSource.java

@Override public Map<String,Object> getValues() throws DataSourceException { final long startNanos=System.nanoTime(); final HashMap<String,Object> values=new HashMap<String,Object>(); Socket sock=null; try { SocketAddress sockAddr=new InetSocketAddress(host,port); sock=new Socket(); sock.connect(sockAddr,(int)timeout.getMillis()); values.put(configHashKeyMap.get(CONNECT_CHECK_RESULT),SUCCESSFUL_CONNECT_RESULT); values.put(configHashKeyMap.get(CONNECT_TEST_MESSAGE),SUCCESSFUL_CONNECT_MESSAGE); } catch ( Exception ex) { values.put(configHashKeyMap.get(CONNECT_CHECK_RESULT),FAILED_CONNECT_RESULT); Throwable t=ex; while (t.getCause() != null) t=t.getCause(); values.put(configHashKeyMap.get(CONNECT_TEST_MESSAGE),t.toString()); } finally { long endNanos=System.nanoTime(); double connectMillis=(double)(endNanos - startNanos) / NANOS_PER_MILLI; values.put(configHashKeyMap.get(CONNECT_TEST_TIME_MS),connectMillis); if (sock != null) { try { sock.close(); } catch ( IOException ioEx) { log.warn(ioEx); } } } return values; }
Example 26
From project arquillian-extension-android, under directory /android-impl/src/main/java/org/jboss/arquillian/android/impl/.
Source file: EmulatorShutdown.java

/** * Sends a user command to the running emulator via its telnet interface. * @param port The emulator's telnet port. * @param command The command to execute on the emulator's telnet interface. * @return Whether sending the command succeeded. */ private Callable<Boolean> sendEmulatorCommand(final int port,final String command){ return new Callable<Boolean>(){ public Boolean call() throws IOException { Socket socket=null; BufferedReader in=null; PrintWriter out=null; try { socket=new Socket("127.0.0.1",port); out=new PrintWriter(socket.getOutputStream(),true); in=new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { return false; } out.write(command); out.write("\r\n"); } finally { try { out.close(); in.close(); socket.close(); } catch ( Exception e) { } } return true; } } ; }
Example 27
From project asterisk-java, under directory /src/main/java/org/asteriskjava/util/internal/.
Source file: SocketConnectionFacadeImpl.java

/** * Creates a new instance for use with the Manager API that uses the given line delimiter. * @param host the foreign host to connect to. * @param port the foreign port to connect to. * @param ssl <code>true</code> to use SSL, <code>false</code> otherwise. * @param timeout 0 incidcates default * @param readTimeout see {@link Socket#setSoTimeout(int)} * @param lineDelimiter a {@link Pattern} for matching the line delimiter for the socket * @throws IOException if the connection cannot be established. */ public SocketConnectionFacadeImpl(String host,int port,boolean ssl,int timeout,int readTimeout,Pattern lineDelimiter) throws IOException { Socket socket; if (ssl) { socket=SSLSocketFactory.getDefault().createSocket(); } else { socket=SocketFactory.getDefault().createSocket(); } socket.setSoTimeout(readTimeout); socket.connect(new InetSocketAddress(host,port),timeout); initialize(socket,lineDelimiter); if (System.getProperty(Trace.TRACE_PROPERTY,"false").equalsIgnoreCase("true")) { trace=new FileTrace(socket); } }
Example 28
From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/util/.
Source file: ViewServer.java

/** * Main server loop. */ public void run(){ while (Thread.currentThread() == mThread) { try { Socket client=mServer.accept(); if (mThreadPool != null) { mThreadPool.submit(new ViewServerWorker(client)); } else { try { client.close(); } catch ( IOException e) { e.printStackTrace(); } } } catch ( Exception e) { Log.w(LOG_TAG,"Connection error: ",e); } } }
Example 29
From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/ea2/server/.
Source file: TaskServer.java

@Override public void run(){ while (!Thread.interrupted()) { try { Socket clientSocket=server.accept(); synchronized (tasks) { boolean foundTask=false; for ( Task task : tasks.toArray(new Task[0])) { if (!task.isComputing() && !task.hasResult()) { ClientTaskThread ctt=new ClientTaskThread(clientSocket,task); Thread t=new Thread(ctt); t.setDaemon(true); t.start(); foundTask=true; break; } } if (!foundTask) { clientSocket.getOutputStream().write("None\n".getBytes()); clientSocket.close(); } } } catch ( IOException e) { } } }
Example 30
From project blacktie, under directory /jatmibroker-xatmi/src/main/java/org/jboss/narayana/blacktie/jatmibroker/core/transport/hybrid/stomp/.
Source file: StompManagement.java

public static Socket connect(String host,int port,String username,String password) throws IOException, ConnectionException { Socket socket=new Socket(host,port); InputStream inputStream=socket.getInputStream(); OutputStream outputStream=socket.getOutputStream(); Map<String,String> headers=new HashMap<String,String>(); headers.put("login",username); headers.put("passcode",password); Message message=new Message(); message.setCommand("CONNECT"); message.setHeaders(headers); send(message,outputStream); Message received=receive(socket,inputStream); if (received.getCommand().equals("ERROR")) { throw new ConnectionException(Connection.TPESYSTEM,new String(received.getBody())); } log.debug("Created socket: " + socket + " input: "+ inputStream+ "output: "+ outputStream); return socket; }
Example 31
From project BombusLime, under directory /src/org/bombusim/networking/.
Source file: NetworkSocketDataStream.java

public NetworkSocketDataStream(String server,int port) throws UnknownHostException, IOException { this.host=server; this.port=port; LimeLog.i("Socket","Connecting to " + host + ":"+ port,null); socket=new Socket(server,port); socket.setKeepAlive(true); istream=socket.getInputStream(); ostream=socket.getOutputStream(); }
Example 32
From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.
Source file: TransformListener.java

public void run(){ Rule.disableTriggersInternal(); while (true) { if (theServerSocket.isClosed()) { return; } Socket socket=null; try { socket=theServerSocket.accept(); } catch ( IOException e) { if (!theServerSocket.isClosed()) { System.out.println("TransformListener.run : exception from server socket accept " + e); e.printStackTrace(); } return; } if (Transformer.isVerbose()) { System.out.println("TransformListener() : handling connection on port " + socket.getLocalPort()); } try { handleConnection(socket); } catch ( Exception e) { System.out.println("TransformListener() : error handling connection on port " + socket.getLocalPort()); try { socket.close(); } catch ( IOException e1) { } } } }
Example 33
From project camel-zookeeper, under directory /src/test/java/org/apache/camel/component/zookeeper/.
Source file: ZooKeeperTestSupport.java

private static String send4LetterWord(String hp,String cmd) throws IOException { String split[]=hp.split(":"); String host=split[0]; int port; try { port=Integer.parseInt(split[1]); } catch ( RuntimeException e) { throw new RuntimeException("Problem parsing " + hp + e.toString()); } Socket sock=new Socket(host,port); BufferedReader reader=null; try { OutputStream outstream=sock.getOutputStream(); outstream.write(cmd.getBytes()); outstream.flush(); reader=new BufferedReader(new InputStreamReader(sock.getInputStream())); StringBuffer sb=new StringBuffer(); String line; while ((line=reader.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } finally { sock.close(); if (reader != null) { reader.close(); } } }
Example 34
From project cas, under directory /cas-server-integration-memcached/src/test/java/org/jasig/cas/ticket/registry/.
Source file: MemCacheTicketRegistryTests.java

private boolean isMemcachedListening(){ Socket socket=null; try { socket=new Socket("127.0.0.1",11211); return true; } catch ( Exception e) { return false; } finally { if (socket != null) { try { socket.close(); } catch ( IOException e) { } } } }
Example 35
From project caseconductor-platform, under directory /utest-domain-services/src/main/java/com/utest/domain/service/util/.
Source file: TrustedSSLUtil.java

public Socket createSocket(final String host,final int port,final InetAddress localAddress,final int localPort,final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } final int timeout=params.getConnectionTimeout(); final SocketFactory socketfactory=getSSLContext().getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host,port,localAddress,localPort); } else { final Socket socket=socketfactory.createSocket(); final SocketAddress localaddr=new InetSocketAddress(localAddress,localPort); final SocketAddress remoteaddr=new InetSocketAddress(host,port); socket.bind(localaddr); socket.connect(remoteaddr,timeout); return socket; } }
Example 36
From project Cilia_1, under directory /components/tcp-adapter/src/main/java/fr/liglab/adele/cilia/tcp/.
Source file: TCPCollector.java

public void run(){ while (started) { try { Socket s=socket.accept(); Object obj=readObject(new BufferedInputStream(s.getInputStream())); Data data=new Data(obj,"tcp-object"); notifyDataArrival(data); } catch ( IOException e) { e.printStackTrace(); } catch ( ClassNotFoundException e) { e.printStackTrace(); } } }
Example 37
public PServerClient(String host,int port) throws IOException { System.err.println("Connecting to PServer: " + host + ":"+ port); s=new Socket(host,port); is=new DataInputStream(s.getInputStream()); os=new DataOutputStream(s.getOutputStream()); }
Example 38
From project cloudify, under directory /dsl/src/main/java/org/cloudifysource/dsl/utils/.
Source file: IOUtils.java

/** * Checks whether a specified port is occupied. * @param port - port to check. * @return - true if port is occupied */ public static boolean isPortOccupied(final int port){ final Socket sock=new Socket(); logger.fine("Checking port " + port); try { sock.connect(new InetSocketAddress("127.0.0.1",port)); logger.fine("Connected to port " + port); sock.close(); return true; } catch ( final IOException e1) { logger.fine("Port " + port + " is free."); return false; } finally { try { sock.close(); } catch ( final IOException e) { } } }
Example 39
From project clustermeister, under directory /cli/src/main/java/com/github/nethad/clustermeister/provisioning/cli/.
Source file: RemoteLoggingServer.java

@Override public void run(){ try { logger.info("Starting remote logging server on port {}.",serverSocketPort); ServerSocket serverSocket=new ServerSocket(serverSocketPort); while (true) { logger.debug("Waiting for a client to connect."); Socket clientConnection=serverSocket.accept(); logger.debug("Client {} connected",clientConnection.getInetAddress()); String threadName=String.format("[RemoteLoggingClient: %s]",clientConnection.getRemoteSocketAddress()); new Thread(new SocketNode(clientConnection,LogManager.getLoggerRepository()),threadName).start(); } } catch ( Throwable t) { logger.error("Exception while waiting for client connections.",t); } }
Example 40
From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.
Source file: BayeuxClientTest.java

@Test public void testURLWithImplicitPort() throws Exception { final AtomicBoolean listening=new AtomicBoolean(); try { Socket socket=new Socket("localhost",80); socket.close(); listening.set(true); } catch ( ConnectException x) { listening.set(false); } final CountDownLatch latch=new CountDownLatch(1); BayeuxClient client=new BayeuxClient("http://localhost/cometd",LongPollingTransport.create(null,httpClient)){ @Override public void onFailure( Throwable x, Message[] messages){ } } ; client.setDebugEnabled(debugTests()); client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){ public void onMessage( ClientSessionChannel channel, Message message){ Assert.assertFalse(message.isSuccessful()); if (listening.get()) Assert.assertTrue(message.get("exception") instanceof ProtocolException); else Assert.assertTrue(message.get("exception") instanceof ConnectException); latch.countDown(); } } ); client.handshake(); Assert.assertTrue(latch.await(5000,TimeUnit.MILLISECONDS)); disconnectBayeuxClient(client); }
Example 41
From project CommitCoin, under directory /src/com/google/bitcoin/core/.
Source file: TCPNetworkConnection.java

/** * Connect to the given IP address using the port specified as part of the network parameters. Once construction is complete a functioning network channel is set up and running. * @param peerAddress address to connect to. IPv6 is not currently supported by BitCoin. Ifport is not positive the default port from params is used. * @param params Defines which network to connect to and details of the protocol. * @param connectTimeoutMsec Timeout in milliseconds when initially connecting to peer * @param dedupe Whether to avoid parsing duplicate messages from the network (ie from other peers). * @param ver The VersionMessage to announce to the other side of the connection. * @throws IOException if there is a network related failure. * @throws ProtocolException if the version negotiation failed. */ public TCPNetworkConnection(NetworkParameters params,boolean dedupe,VersionMessage ver) throws IOException, ProtocolException { this.params=params; this.myVersionMessage=ver; socket=new Socket(); this.serializer=new BitcoinSerializer(this.params,false,dedupe ? dedupeList : null); this.serializer.setUseChecksumming(Utils.now().after(checksummingProtocolChangeDate)); }
Example 42
From project commons-io, under directory /src/test/java/org/apache/commons/io/.
Source file: IOUtilsTestCase.java

public void testSocketCloseQuietlyOnException(){ IOUtils.closeQuietly(new Socket(){ @Override public void close() throws IOException { throw new IOException(); } } ); }
Example 43
public void run(){ if (handshake == null) handshake=new Handshake(ClientStub.this); try { while (serverSocket != null && serverSocket.isBound() && !Thread.currentThread().isInterrupted()) { Socket socket=serverSocket.accept(); ClientConnection connection=handshake.execute(socket); if (connection != null) { addClient(connection); connection.start(); } } } catch ( IOException e) { logger.info("exception in client connection listener",e); } }
Example 44
From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/.
Source file: CouchbaseMock.java

public HarakiriMonitor(String host,int port,boolean terminate,CouchbaseMock mock) throws IOException { this.mock=mock; this.terminate=terminate; sock=new Socket(host,port); input=new BufferedReader(new InputStreamReader(sock.getInputStream())); output=sock.getOutputStream(); commandHandlers=new HashMap<String,MockControlCommandHandler>(); commandHandlers.put("failover",new FailoverCommandHandler()); commandHandlers.put("respawn",new RespawnCommandHandler()); commandHandlers.put("hiccup",new HiccupCommandHandler()); commandHandlers.put("truncate",new TruncateCommandHandler()); }
Example 45
From project cxf-dosgi, under directory /systests2/common/src/main/java/org/apache/cxf/dosgi/systests2/common/.
Source file: AbstractTestExportService.java

private void waitPort(int port) throws Exception { for (int i=0; i < 20; i++) { Socket s=null; try { s=new Socket((String)null,port); return; } catch ( IOException e) { } finally { if (s != null) { try { s.close(); } catch ( IOException e) { } } } System.out.println("Waiting for server to appear on port: " + port); Thread.sleep(1000); } throw new TimeoutException(); }
Example 46
From project daap, under directory /src/main/java/org/ardverk/daap/nio/.
Source file: DaapServerNIO.java

/** * Accept an icoming connection * @throws IOException */ private void processAccept(SelectionKey sk) throws IOException { if (!sk.isValid()) return; ServerSocketChannel ssc=(ServerSocketChannel)sk.channel(); SocketChannel channel=ssc.accept(); if (channel == null) return; try { Socket socket=channel.socket(); if (channel.isOpen() && accept(socket.getInetAddress())) { channel.configureBlocking(false); DaapConnectionNIO connection=new DaapConnectionNIO(this,channel); channel.register(selector,SelectionKey.OP_READ,connection); addPendingConnection(connection); } else { channel.close(); } } catch ( IOException err) { LOG.error("IOException",err); try { channel.close(); } catch ( IOException iox) { } } }
Example 47
From project dawn-isencia, under directory /com.isencia.passerelle.commons.ume/src/trials/java/com/isencia/message/net/requestreply/.
Source file: EchoClient.java

public static void main(String[] args){ Socket s=null; Writer msgWriter=null; Reader msgReader=null; try { s=new Socket("localhost",3333); msgWriter=new OutputStreamWriter(s.getOutputStream(),"ISO-8859-1"); msgReader=new InputStreamReader(s.getInputStream()); for (int i=0; i < 5; ++i) { msgWriter.write("Hello" + i); msgWriter.write(RECORD_SEPARATOR); msgWriter.write(EOF); msgWriter.flush(); } for (int i=0; i < 5; ++i) { IMessageExtractor extractor=new EndOfMsgCharMsgExtractor(); extractor.open(msgReader); System.out.println("Received echo msg : " + extractor.getMessage()); } msgWriter.write("Q"); msgWriter.write(RECORD_SEPARATOR); msgWriter.flush(); } catch ( Exception e) { e.printStackTrace(); } finally { if (s != null) try { s.close(); } catch ( Exception e) { } } }
Example 48
From project accent, under directory /src/test/java/net/lshift/accent/.
Source file: ControlledConnectionProxy.java

public void run(){ try { this.inServer=new ServerSocket(listenPort); inServer.setReuseAddress(true); this.inSock=inServer.accept(); this.outSock=new Socket(host,port); DataInputStream iis=new DataInputStream(this.inSock.getInputStream()); DataOutputStream ios=new DataOutputStream(this.inSock.getOutputStream()); DataInputStream ois=new DataInputStream(this.outSock.getInputStream()); DataOutputStream oos=new DataOutputStream(this.outSock.getOutputStream()); byte[] handshake=new byte[8]; iis.readFully(handshake); oos.write(handshake); BlockingCell<Exception> wio=new BlockingCell<Exception>(); new Thread(new DirectionHandler(wio,true,iis,oos)).start(); new Thread(new DirectionHandler(wio,false,ois,ios)).start(); waitAndLogException(wio); } catch ( Exception e) { reportAndLogNonNullException(e); } finally { try { if (this.inSock != null) this.inSock.close(); } catch ( Exception e) { logException(e); } try { if (this.outSock != null) this.outSock.close(); } catch ( Exception e) { logException(e); } this.reportEnd.setIfUnset(null); } }
Example 49
From project aksunai, under directory /src/org/androidnerds/app/aksunai/net/.
Source file: ConnectionThread.java

public void run(){ try { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"Connecting to... " + mServerDetail.mUrl + ":"+ mServerDetail.mPort); mSock=new Socket(mServerDetail.mUrl,mServerDetail.mPort); } catch ( UnknownHostException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"UnknownHostException caught, terminating connection process"); } catch ( IOException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"IOException caught on socket creation. (Server) " + mServer + ", (Exception) "+ e.toString()); } try { mWriter=new BufferedWriter(new OutputStreamWriter(mSock.getOutputStream())); mReader=new BufferedReader(new InputStreamReader(mSock.getInputStream())); } catch ( IOException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"IOException caught grabbing input/output streams. (Server) " + mServer + ", (Exception) "+ e.toString()); } mServer.init(mServerDetail.mPass,mServerDetail.mNick,mServerDetail.mUser,mServerDetail.mRealName); try { while (!shouldKill()) { String message=mReader.readLine(); if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"Received message: " + message); mServer.receiveMessage(message); } } catch ( IOException e) { if (AppConstants.DEBUG) Log.d(AppConstants.NET_TAG,"IOException caught handling messages. (Server) " + mServer + ", (Exception) "+ e.toString()); } return; }
Example 50
From project chililog-server, under directory /src/test/java/org/chililog/client/stomp/.
Source file: Client.java

/** * Connects to a server Example: <pre> Client stomp_client = new Client( "host.com", 61626 ); stomp_client.subscribe( "/my/messages" ); ... </pre> * @see Stomp * @param server The IP or host name of the server * @param port The port the server is listening on */ public Client(String server,int port,String login,String pass) throws IOException, LoginException { _socket=new Socket(server,port); _input=_socket.getInputStream(); _output=_socket.getOutputStream(); _listener=new Receiver(this,_input); _listener.start(); HashMap header=new HashMap(); header.put("login",login); header.put("passcode",pass); transmit(Command.CONNECT,header,null); try { String error=null; while (!isConnected() && ((error=nextError()) == null)) { Thread.sleep(100); } if (error != null) throw new LoginException(error); } catch ( InterruptedException e) { } }
Example 51
From project com.juick.android, under directory /src/com/juick/android/.
Source file: WsClient.java

public boolean connect(String host,int port,String location,String headers){ try { sock=new Socket(host,port); is=sock.getInputStream(); os=sock.getOutputStream(); String handshake="GET " + location + " HTTP/1.1\r\n"+ "Host: "+ host+ "\r\n"+ "Connection: Upgrade\r\n"+ "Upgrade: WebSocket\r\n"+ "Origin: http://juick.com/\r\n"+ "Sec-WebSocket-Key1: 9 9 9 9\r\n"+ "Sec-WebSocket-Key2: 8 8 8 8 8\r\n"+ "Sec-WebSocket-Protocol: sample\r\n"; if (headers != null) { handshake+=headers; } handshake+="\r\n" + "12345678"; os.write(handshake.getBytes()); return true; } catch ( Exception e) { System.err.println(e); return false; } }
Example 52
From project com.juick.xmpp, under directory /src/com/juick/xmpp/.
Source file: XmppConnection.java

public boolean openStreams(final String host,int port,boolean use_ssl){ try { if (!use_ssl) { connection=new Socket(host,port); } else { connection=SSLSocketFactory.getDefault().createSocket(host,port); } restartParser(); writer=new OutputStreamWriter(connection.getOutputStream()); } catch ( Exception e) { return false; } return true; }
Example 53
From project android-bankdroid, under directory /src/eu/nullbyte/android/urllib/.
Source file: EasySSLSocketFactory.java

/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,java.lang.String,int,java.net.InetAddress,int,org.apache.http.params.HttpParams) */ public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout=HttpConnectionParams.getConnectionTimeout(params); int soTimeout=HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress=new InetSocketAddress(host,port); SSLSocket sslsock=(SSLSocket)((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { if (localPort < 0) { localPort=0; } InetSocketAddress isa=new InetSocketAddress(localAddress,localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress,connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
Example 54
From project android-client_1, under directory /src/com/googlecode/asmack/connection/impl/.
Source file: FeatureNegotiationEngine.java

/** * Create a new FeatureNegotiationEngine for a given tcp socket. * @param socket Socket The basic socket. * @throws XmlPullParserException If the pull parser can't be created. * @throws IOException When there is an IOException during intialization. * @throws XmppTransportException When this connection failes. */ public FeatureNegotiationEngine(Socket socket) throws XmlPullParserException, IOException, XmppTransportException { Log.d("BC/XMPP","start feature negotiation"); this.socket=socket; this.inputStream=socket.getInputStream(); this.outputStream=socket.getOutputStream(); xmppOutput=new XmppOutputStream(outputStream); xmppInput=new XmppInputStream(inputStream); }
Example 55
From project ardverk-commons, under directory /src/main/java/org/ardverk/io/.
Source file: IoUtils.java

/** * Closes the given {@code Object}. Returns {@code true} on successand {@code false} on failure. All {@link IOException}s will be caught and no error will be thrown if the Object isn't any of the supported types. * @see Closeable * @see #close(Closeable) * @see AutoCloseable * @see #close(AutoCloseable) * @see Socket * @see #close(Socket) * @see ServerSocket * @see #close(ServerSocket) * @see DatagramSocket * @see #close(DatagramSocket) * @see AtomicReference * @see #close(AtomicReference) */ public static boolean close(Object o){ if (o instanceof Closeable) { return close((Closeable)o); } else if (o instanceof AutoCloseable) { return close((AutoCloseable)o); } else if (o instanceof Socket) { return close((Socket)o); } else if (o instanceof ServerSocket) { return close((ServerSocket)o); } else if (o instanceof DatagramSocket) { return close((DatagramSocket)o); } else if (o instanceof AtomicReference<?>) { return close(((AtomicReference<?>)o)); } return false; }
Example 56
From project AsmackService, under directory /src/com/googlecode/asmack/connection/impl/.
Source file: FeatureNegotiationEngine.java

/** * Create a new FeatureNegotiationEngine for a given tcp socket. * @param socket Socket The basic socket. * @throws XmlPullParserException If the pull parser can't be created. * @throws IOException When there is an IOException during intialization. * @throws XmppTransportException When this connection failes. */ public FeatureNegotiationEngine(Socket socket) throws XmlPullParserException, IOException, XmppTransportException { this.socket=socket; this.inputStream=socket.getInputStream(); this.outputStream=socket.getOutputStream(); xmppOutput=new XmppOutputStream(outputStream); xmppInput=new XmppInputStream(inputStream); }
Example 57
From project bbb-java, under directory /src/main/java/org/transdroid/util/.
Source file: FakeSocketFactory.java

@Override public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout=HttpConnectionParams.getConnectionTimeout(params); int soTimeout=HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress=new InetSocketAddress(host,port); SSLSocket sslsock=(SSLSocket)((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { if (localPort < 0) { localPort=0; } InetSocketAddress isa=new InetSocketAddress(localAddress,localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress,connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
Example 58
From project BHT-FPA, under directory /patterns-codebeispiele/de.bht.fpa.examples.proxypattern/de.bht.fpa.examples.proxypattern.coffemachine.proxy/src/de/bht/fpa/proxypattern/coffemachine/proxy/.
Source file: CoffeMachineRemoteServiceDecorator.java

private void handleClient(final Socket client){ System.out.println(getClass().getName() + " got connection: " + client.getInetAddress()); new Thread(){ @Override public void run(){ try { ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream()); ObjectInputStream ois=new ObjectInputStream(client.getInputStream()); while (client.isConnected()) { handleCommand(ois,oos); } } catch ( Exception e) { e.printStackTrace(); } } } .start(); }
Example 59
From project Citizens, under directory /src/core/net/citizensnpcs/resources/npclib/.
Source file: NPCNetworkManager.java

public NPCNetworkManager(Socket paramSocket,String paramString,NetHandler paramNetHandler,PrivateKey key) throws IOException { super(paramSocket,paramString,paramNetHandler,key); if (THREAD_STOPPER != null) { try { THREAD_STOPPER.set(this,false); } catch ( Exception e) { } } }
Example 60
From project cmsandroid, under directory /src/com/zia/freshdocs/net/.
Source file: EasySSLSocketFactory.java

/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,java.lang.String,int,java.net.InetAddress,int,org.apache.http.params.HttpParams) */ public Socket connectSocket(Socket sock,String host,int port,InetAddress localAddress,int localPort,HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout=HttpConnectionParams.getConnectionTimeout(params); int soTimeout=HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress=new InetSocketAddress(host,port); SSLSocket sslsock=(SSLSocket)((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { if (localPort < 0) { localPort=0; } InetSocketAddress isa=new InetSocketAddress(localAddress,localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress,connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
Example 61
From project cornerstone, under directory /frameworks/base/services/java/com/android/server/wm/.
Source file: WindowManagerService.java

/** * Lists all availble windows in the system. The listing is written in the specified Socket's output stream with the following syntax: windowHashCodeInHexadecimal windowName Each line of the ouput represents a different window. * @param client The remote client to send the listing to. * @return False if an error occured, true otherwise. */ boolean viewServerListWindows(Socket client){ if (isSystemSecure()) { return false; } boolean result=true; WindowState[] windows; synchronized (mWindowMap) { windows=mWindows.toArray(new WindowState[mWindows.size()]); } BufferedWriter out=null; try { OutputStream clientStream=client.getOutputStream(); out=new BufferedWriter(new OutputStreamWriter(clientStream),8 * 1024); final int count=windows.length; for (int i=0; i < count; i++) { final WindowState w=windows[i]; out.write(Integer.toHexString(System.identityHashCode(w))); out.write(' '); out.append(w.mAttrs.getTitle()); out.write('\n'); } out.write("DONE.\n"); out.flush(); } catch ( Exception e) { result=false; } finally { if (out != null) { try { out.close(); } catch ( IOException e) { result=false; } } } return result; }