Java Code Examples for java.net.Socket.getOutputStream()

The following are Jave code examples for showing how to use getOutputStream() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: Http2TestServerConnection.java   View Source Code Vote up 6 votes
Http2TestServerConnection(Http2TestServer server, Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        handshake(server.serverName(), (SSLSocket)socket);
    }
    System.err.println("TestServer: New connection from " + socket);
    this.server = server;
    this.streams = Collections.synchronizedMap(new HashMap<>());
    this.outputQ = new Queue<>();
    this.socket = socket;
    this.serverSettings = SettingsFrame.getDefaultSettings();
    this.exec = server.exec;
    this.secure = server.secure;
    this.pushStreams = new HashSet<>();
    is = new BufferedInputStream(socket.getInputStream());
    os = new BufferedOutputStream(socket.getOutputStream());
}
 
Example 2
Project: VirtualAPK   File: TCPServerService.java   View Source Code Vote up 6 votes
private void responseClient(Socket client) throws IOException {
    // 用于接收客户端消息
    BufferedReader in = new BufferedReader(new InputStreamReader(
            client.getInputStream()));
    // 用于向客户端发送消息
    PrintWriter out = new PrintWriter(new BufferedWriter(
            new OutputStreamWriter(client.getOutputStream())), true);
    out.println("欢迎来到聊天室!");
    while (!mIsServiceDestoryed) {
        String str = in.readLine();
        System.out.println("msg from client:" + str);
        if (str == null) {
            break;
        }
        int i = new Random().nextInt(mDefinedMessages.length);
        String msg = mDefinedMessages[i];
        out.println(msg);
        System.out.println("send :" + msg);
    }
    System.out.println("client quit.");
    // 关闭流
    MyUtils.close(out);
    MyUtils.close(in);
    client.close();
}
 
Example 3
Project: featurea   File: TcpSlave.java   View Source Code Vote up 6 votes
TcpConnectionHandler(Socket socket) throws ModbusInitException {
    this.socket = socket;
    try {
        transport = new TestableTransport(socket.getInputStream(), socket.getOutputStream());
    } catch (IOException e) {
        throw new ModbusInitException(e);
    }
}
 
Example 4
Project: ibm-cos-sdk-java   File: MockServer.java   View Source Code Vote up 6 votes
@Override
public void runServer(ServerSocket serverSocket) {
    try {
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                StringBuilder builder = new StringBuilder();
                builder.append(response.getStatusLine().toString() + "\r\n");
                for (Header header : response.getAllHeaders()) {
                    builder.append(header.getName() + ":" + header.getValue() + "\r\n");
                }
                builder.append("\r\n");
                builder.append(content);
                System.out.println(builder.toString());
                out.writeBytes(builder.toString());
            } catch (SocketException se) {
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Error when waiting for new socket connection.", e);
    }
}
 
Example 5
Project: scorekeeperfrontend   File: TimerClient.java   View Source Code Vote up 5 votes
public TimerClient(InetSocketAddress addr) throws IOException
{
	sock = new Socket();
	sock.connect(addr);
	in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
	out = sock.getOutputStream();
	done = true;
}
 
Example 6
Project: Dist_HW_2   File: LamportMutex.java   View Source Code Vote up 5 votes
/**
 * Initialize a new outgoing connection. 
 */
private void initIncomingConnection(Socket sock) throws IOException{
	server.log.log(Level.FINER, "Initializing connection with new server");
	
	PrintWriter pw = new PrintWriter(sock.getOutputStream());
	BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
	
	// listen for INIT message from unknown server
	String msg = br.readLine();
	LamportMessage lm = LamportMessage.fromString(msg);
	
	// invalid message ... break connection
	if(lm==null || lm.type!=LamportMessageType.INIT_REQUEST){
		sock.close();
		return;
	}
	
	// get serverID
	int iServer = lm.serverID; 					
	
	if(lamportSockets[iServer] != null){
		server.log.log(Level.WARNING, "Imposter attempt from server ID "+ iServer);
		sock.close();
		return;
	}
					
	initConnectionCommon(sock, pw, br, iServer);

	// respond with current data
	// and current number of servers
	LamportMessage respond = LamportMessage.INIT_RESPOND(serverID, nServers, clock, server.getSerializedData());
	sendMessage(iServer, respond.toString());

}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: BioSender.java   View Source Code Vote up 5 votes
/**
 * open real socket and set time out when waitForAck is enabled
 * is socket open return directly
 */
protected void openSocket() throws IOException {
   if(isConnected()) return ;
   try {
       socket = new Socket();
       InetSocketAddress sockaddr = new InetSocketAddress(getAddress(), getPort());
       socket.connect(sockaddr,(int)getTimeout());
       socket.setSendBufferSize(getTxBufSize());
       socket.setReceiveBufferSize(getRxBufSize());
       socket.setSoTimeout( (int) getTimeout());
       socket.setTcpNoDelay(getTcpNoDelay());
       socket.setKeepAlive(getSoKeepAlive());
       socket.setReuseAddress(getSoReuseAddress());
       socket.setOOBInline(getOoBInline());
       socket.setSoLinger(getSoLingerOn(),getSoLingerTime());
       socket.setTrafficClass(getSoTrafficClass());
       setConnected(true);
       soOut = socket.getOutputStream();
       soIn  = socket.getInputStream();
       setRequestCount(0);
       setConnectTime(System.currentTimeMillis());
       if (log.isDebugEnabled())
           log.debug(sm.getString("IDataSender.openSocket", getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)));
  } catch (IOException ex1) {
      SenderState.getSenderState(getDestination()).setSuspect();
      if (log.isDebugEnabled())
          log.debug(sm.getString("IDataSender.openSocket.failure",getAddress().getHostAddress(), Integer.valueOf(getPort()), Long.valueOf(0)), ex1);
      throw (ex1);
    }
    
 }
 
Example 8
Project: LotusCloud   File: ProxyServer.java   View Source Code Vote up 5 votes
private static String[] connect(String host, int port) {
    try {
        Socket socket = new Socket(host, port);
        socket.setSoTimeout(5000);

        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        DataInputStream in = new DataInputStream(socket.getInputStream());

        out.write(0xFE);

        int b;
        StringBuilder str = new StringBuilder();
        while ((b = in.read()) != -1) {
            if (b != 0 && b > 16 && b != 255 && b != 23 && b != 24) {
                str.append((char) b);
            }
        }

        String[] data = str.toString().split("§");
        return data;
    } catch (IOException ex) {
        if (!ex.getMessage().toLowerCase().contains("connection refused")) {
            ex.printStackTrace();
        }
    }

    String[] notOnline = {"error: not online", "0", "0"};
    return notOnline;
}
 
Example 9
Project: kite   File: SocketStream.java   View Source Code Vote up 5 votes
public SocketStream(Scheme scheme, String host, Integer port,
                    Preprocessor<String,Microblog> preprocessor) {
    setScheme(scheme);
    this.host = host;
    this.port = port;
    this.preprocessor = preprocessor;

    try {
        socket = new Socket(host, port);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);
    } catch (Exception e) {
    }
}
 
Example 10
Project: CrypDist   File: Client.java   View Source Code Vote up 5 votes
public void initialization() {

        //Establish a connection with server, get number of active peers and their information.
        try {
            Thread t2 = new ReceiveServerRequest(this);
            t2.start();

            Socket serverConnection = new Socket(swAdr, swPort);
            serverConnection.setSoTimeout(Config.SERVER_TIMEOUT);

            DataInputStream in = new DataInputStream(serverConnection.getInputStream());

            receivePeerList(in);

            //Send itself data to server.
            DataOutputStream out = new DataOutputStream(serverConnection.getOutputStream());
            out.writeInt(heartBeatPort);
            out.writeInt(serverPort);
            out.writeUTF(Config.USER_NAME);
            out.writeUTF(Config.USER_PASS);
            out.flush();

            boolean authenticated = in.readBoolean();
            active = in.readBoolean();
            crypDist.setActive(active);
            int size = in.readInt();
            byte[] key_array = new byte[size];
            in.read(key_array);

            crypDist.setSessionKey(key_array);
            crypDist.setAuthenticated(authenticated);

            serverConnection.close();
        }
        catch(IOException e)
        {
            log.warn("Cannot connect to the server, terminated.");
            log.warn(e);
        }
    }
 
Example 11
Project: incubator-netbeans   File: RemoteAgent.java   View Source Code Vote up 5 votes
void commandLoop(Socket socket) throws IOException {
    // in before out -- so we don't hang the controlling process
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
    OutputStream socketOut = socket.getOutputStream();
    System.setOut(new PrintStream(new MultiplexingOutputStream("out", socketOut), true));
    System.setErr(new PrintStream(new MultiplexingOutputStream("err", socketOut), true));
    ObjectOutputStream out = new ObjectOutputStream(new MultiplexingOutputStream("command", socketOut));
    while (true) {
        int cmd = in.readInt();
        performCommand(cmd, in, out);
    }
}
 
Example 12
Project: socket-client-server   File: TCPClient.java   View Source Code Vote up 5 votes
private void connectActually(){
    try {
        mSocket = new Socket(this.ip,this.port);
        mSocket.setTcpNoDelay(true);
        mSocket.setReuseAddress(true);
        mDataInputStream = new DataInputStream(mSocket.getInputStream());
        mDataOutputStream = new DataOutputStream(mSocket.getOutputStream());
    } catch (IOException e) {
        if(mTCPResultListener !=null){
            mTCPResultListener.onConnectFailed(e.getMessage());
        }

    }
}
 
Example 13
Project: flume-release-1.7.0   File: TestNetcatSource.java   View Source Code Vote up 5 votes
private void sendEvent(Socket socket, String content, String encoding) throws IOException {
  OutputStream output = socket.getOutputStream();
  IOUtils.write(content + IOUtils.LINE_SEPARATOR_UNIX, output, encoding);
  output.flush();
}
 
Example 14
Project: Progetto-A   File: Client.java   View Source Code Vote up 5 votes
/**
 * 
 * @param socket socket per la comunicazione
 * @throws IOException lanciata quando si verifica un errore di input output
 */
public Client(Socket socket) throws IOException {
    this.daGiocatore = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    this.aGiocatore = new PrintWriter(socket.getOutputStream(), true);
    this.socket = socket;

}
 
Example 15
Project: T0rlib4j   File: Utilities.java   View Source Code Vote up 5 votes
public static Socket socks4aSocketConnection(String networkHost, int networkPort, String socksHost, int socksPort)
        throws IOException {

    Socket socket = new Socket();
    socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
    SocketAddress socksAddress = new InetSocketAddress(socksHost, socksPort);
    socket.connect(socksAddress, CONNECT_TIMEOUT_MILLISECONDS);

    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
    outputStream.write((byte) 0x04);
    outputStream.write((byte) 0x01);
    outputStream.writeShort((short) networkPort);
    outputStream.writeInt(0x01);
    outputStream.write((byte) 0x00);
    outputStream.write(networkHost.getBytes());
    outputStream.write((byte) 0x00);

    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
    byte firstByte = inputStream.readByte();
    byte secondByte = inputStream.readByte();
    if (firstByte != (byte) 0x00 || secondByte != (byte) 0x5a) {
        socket.close();
        throw new IOException("SOCKS4a connect failed, got " + firstByte + " - " + secondByte +
                ", but expected 0x00 - 0x5a");
    }
    inputStream.readShort();
    inputStream.readInt();
    return socket;
}
 
Example 16
Project: SocketGames   File: GameServer.java   View Source Code Vote up 4 votes
/**
 * Opens a server port to listen for incoming network requests. When a request
 * is received, accepts the connection, wraps the resulting socket in a thread,
 * and starts the thread process.
 * 
 * @param args[0]
 *            the port to use when listening for connections; if no command line
 *            arguments are provided, uses the default
 * @param args[1]
 *            the max number of concurrent connections to accept; if no command
 *            line arguments, uses the default
 * @throws java.io.IOException
 *             if unable to read from socket
 */
public static void main(String[] args) throws IOException {
	int desiredPort = DEFAULT_PORT_NUM;
	int maxConnections = DEFAULT_MAX_USERS;
	boolean createLogFile = false;
	try {
		desiredPort = Integer.parseInt(args[0]);
		maxConnections = Integer.parseInt(args[1]);
		createLogFile = Boolean.parseBoolean(args[2]);
	} catch (ArrayIndexOutOfBoundsException
			| NumberFormatException e) {
		LOGGER.info(
				"Command line arguments missing or faulty.  Launching with program defaults.");
	} 
	if (createLogFile) attachLogFileHandler();
	String refuseNewConnectionMessage = "The server limit of " + maxConnections
			+ ((maxConnections == 1) ? " connection"
					: " connections")
			+ " has been reached.  Please try again, later.";

	try (ServerSocket socketRequestListener = new ServerSocket(
			desiredPort)) {
		LOGGER.info("GameServer started on port: "
				+ socketRequestListener.getLocalPort()
				+ ".  Maximum simultaneous users: "
				+ maxConnections);
		GameTracker.initialize();
		while (true) {
			// the following call blocks until a connection is made
			Socket socket = socketRequestListener.accept();
			InetAddress remoteMachine = socket.getInetAddress();
			// String remoteHost = remoteMachine.getHostName();
			LOGGER.info("Incoming connection request from " + remoteMachine);

			int numActiveSockets = Thread.activeCount() - 1;
			if (numActiveSockets < maxConnections) {
				new Thread(new GameThread(socket)).start();
				numActiveSockets++;
				LOGGER.info("HELLO " + remoteMachine
						+ ".  Number of current connections: "
						+ numActiveSockets);
			} else {
				PrintWriter out = new PrintWriter(
						socket.getOutputStream());
				out.println(refuseNewConnectionMessage);
				out.close();
				socket.close();
				LOGGER.warning("SORRY " + remoteMachine
						+ ".  Number of current connections: "
						+ numActiveSockets);
			}
		}
	}
}
 
Example 17
Project: monarch   File: HandShake.java   View Source Code Vote up 4 votes
/**
 * HandShake Constructor used by server side connection
 */
public HandShake(Socket sock, int timeout, DistributedSystem sys, Version clientVersion,
    byte communicationMode) throws IOException, AuthenticationRequiredException {
  this.clientVersion = clientVersion;
  this.system = sys;
  // SocketChannel sc = sock.getChannel();
  /*
   * if (sc != null) { } else
   */ {
    int soTimeout = -1;
    try {
      soTimeout = sock.getSoTimeout();
      sock.setSoTimeout(timeout);
      InputStream is = sock.getInputStream();
      int valRead = is.read();
      // this.code = (byte)is.read();
      if (valRead == -1) {
        throw new EOFException(
            LocalizedStrings.HandShake_HANDSHAKE_EOF_REACHED_BEFORE_CLIENT_CODE_COULD_BE_READ
                .toLocalizedString());
      }
      this.code = (byte) valRead;
      if (this.code != REPLY_OK) {
        throw new IOException(
            LocalizedStrings.HandShake_HANDSHAKE_REPLY_CODE_IS_NOT_OK.toLocalizedString());
      }
      try {
        DataInputStream dis = new DataInputStream(is);
        DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
        this.clientReadTimeout = dis.readInt();
        if (clientVersion.compareTo(Version.CURRENT) < 0) {
          // versioned streams allow object serialization code to deal with older clients
          dis = new VersionedDataInputStream(dis, clientVersion);
          dos = new VersionedDataOutputStream(dos, clientVersion);
        }
        this.id = ClientProxyMembershipID.readCanonicalized(dis);
        // Note: credentials should always be the last piece in handshake for
        // Diffie-Hellman key exchange to work
        if (clientVersion.compareTo(Version.GFE_603) >= 0) {
          setOverrides(new byte[] {dis.readByte()});
        } else {
          setClientConflation(dis.readByte());
        }
        // Hitesh
        if (this.clientVersion.compareTo(Version.GFE_65) < 0
            || communicationMode == Acceptor.GATEWAY_TO_GATEWAY) {
          this.credentials = readCredentials(dis, dos, sys);
        } else {
          this.credentials = this.readCredential(dis, dos, sys);
        }
      } catch (IOException ioe) {
        this.code = -2;
        throw ioe;
      } catch (ClassNotFoundException cnfe) {
        this.code = -3;
        throw new IOException(
            LocalizedStrings.HandShake_CLIENTPROXYMEMBERSHIPID_CLASS_COULD_NOT_BE_FOUND_WHILE_DESERIALIZING_THE_OBJECT
                .toLocalizedString());
      }
    } finally {
      if (soTimeout != -1) {
        try {
          sock.setSoTimeout(soTimeout);
        } catch (IOException ignore) {
        }
      }
    }
  }
}
 
Example 18
Project: jdk8u-jdk   File: TestFtpClientNameListWithNull.java   View Source Code Vote up 4 votes
public void handleClient(Socket client) throws IOException {
    boolean done = false;
    String str;

    client.setSoTimeout(2000);
    BufferedReader in = new BufferedReader(new InputStreamReader(client.
            getInputStream()));
    PrintWriter out = new PrintWriter(client.getOutputStream(), true);
    out.println("220 FTP serverSocket is ready.");
    while (!done) {
        try {
            str = in.readLine();
        } catch (SocketException e) {
            done = true;
            continue;
        }
        String cmd = str.substring(0, str.indexOf(" ") > 0 ?
                str.indexOf(" ") : str.length());
        String args = (cmd.equals(str)) ?
                "" : str.substring(str.indexOf(" "));
        switch (cmd) {
            case "QUIT":
                out.println("221 Goodbye.");
                out.flush();
                done = true;
                break;
            case "EPSV":
                if ("all".equalsIgnoreCase(args)) {
                    out.println("200 EPSV ALL command successful.");
                    continue;
                }
                out.println("229 Entering Extended Passive Mode " +
                        "(|||" + getPort() + "|)");
                break;
            case "NLST":
                if (args.trim().length() != 0) {
                    commandHasArgs = true;
                }
                out.println("200 Command okay.");
                break;
            default:
                out.println("500 unsupported command: " + str);
        }
    }
}
 
Example 19
Project: EvoMaster   File: AgentController.java   View Source Code Vote up 4 votes
public static void start(int port){

        try{
            socket = new Socket("localhost", port);
            out = new ObjectOutputStream(socket.getOutputStream());
            in = new ObjectInputStream(socket.getInputStream());
        } catch (Exception e){
            SimpleLogger.error("Failure in Java Agent: "+e.getMessage(), e);
        }

        SimpleLogger.info("Connected to EvoMaster controller");

        thread = new Thread(() ->{

            while (! Thread.interrupted() && socket != null){

                Object msg;

                try {
                    msg = in.readObject();
                } catch (IOException e) {
                    SimpleLogger.error("Failure in receiving message: "+e.getMessage());
                    return;
                } catch (ClassNotFoundException e) {
                    SimpleLogger.error("Configuration error: "+e.getMessage());
                    return;
                }

                if(msg == null || ! (msg instanceof Command)){
                    SimpleLogger.error("Received wrong message type: "+msg);
                    continue;
                }

                Command command = (Command) msg;
                long start = System.currentTimeMillis();
                SimpleLogger.debug("Handling command: "+command);

                switch(command){
                    case NEW_SEARCH:
                        InstrumentationController.resetForNewSearch();
                        sendObject(Command.ACK);
                        break;
                    case NEW_TEST:
                        InstrumentationController.resetForNewTest();
                        sendObject(Command.ACK);
                        break;
                    case TARGET_INFOS:
                        handleTargetInfos();
                        break;
                    case ACTION_INDEX:
                        handleActionIndex();
                        sendObject(Command.ACK);
                        break;
                    default:
                        SimpleLogger.error("Unrecognized command: "+command);
                        return;
                }

                long delta = System.currentTimeMillis() - start;
                SimpleLogger.debug("Command took "+delta+" ms");
            }
        });

        thread.start();
    }
 
Example 20
Project: Pogamut3   File: NetworkLogManager.java   View Source Code Vote up 2 votes
/**
 * Wraps 'socket' with a service layer providing a means for sending {@link NetworkLogEnvelope}s through it.
 * @param socket
 * @throws IOException
 */
public LogSocket(Socket socket) throws IOException {
	this.socket = socket;
	this.writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), encoder));
}