java.net.Socket.getOutputStream()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(486)

本文整理了Java中java.net.Socket.getOutputStream()方法的一些代码示例,展示了Socket.getOutputStream()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Socket.getOutputStream()方法的具体详情如下:
包路径:java.net.Socket
类名称:Socket
方法名:getOutputStream

Socket.getOutputStream介绍

[英]Returns an output stream to write data into this socket.
[中]返回将数据写入此套接字的输出流。

代码示例

代码示例来源:origin: iluwatar/java-design-patterns

@Override
public void run() {
 try (Socket socket = new Socket(InetAddress.getLocalHost(), serverPort)) {
  OutputStream outputStream = socket.getOutputStream();
  PrintWriter writer = new PrintWriter(outputStream);
  sendLogRequests(writer, socket.getInputStream());
 } catch (IOException e) {
  LOGGER.error("error sending requests", e);
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: alibaba/canal

BioSocketChannel(Socket socket) throws IOException{
  this.socket = socket;
  this.input = new BufferedInputStream(socket.getInputStream(), 16384);
  this.output = socket.getOutputStream();
}

代码示例来源:origin: apache/flink

private void createConnection() throws IOException {
  client = new Socket(hostName, port);
  client.setKeepAlive(true);
  client.setTcpNoDelay(true);
  outputStream = client.getOutputStream();
}

代码示例来源:origin: facebook/stetho

private IRCClientConnection(
  StethoReporter reporter,
  Socket socket,
  String charset)
  throws IOException {
 mReporter = reporter;
 mSocket = socket;
 mInput = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset));
 mOutput = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset));
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Returs a Tree from the server connected to at host:port.
 */
public Tree getTree(String query) 
 throws IOException
{
 Socket socket = new Socket(host, port);
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("tree " + query + "\n");
 out.flush();
 ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
 Object o;
 try {
  o = ois.readObject();
 } catch (ClassNotFoundException e) {
  throw new RuntimeException(e);
 }
 if (!(o instanceof Tree)) {
  throw new IllegalArgumentException("Expected a tree");
 }
 Tree tree = (Tree) o;
 socket.close();
 return tree;
}

代码示例来源:origin: stackoverflow.com

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
 out.println("output");
 if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
 System.out.println(clientSocket.isConnected());
 System.out.println(clientSocket.getInputStream().read());
    // thread sleep ...
 // break condition , close sockets and the like ...
}

代码示例来源:origin: wildfly/wildfly

public void init(String local_addr, String remote_addr, int local_port, int remote_port) throws Exception {
  local=new InetSocketAddress(local_addr, local_port);
  remote=new InetSocketAddress(remote_addr, remote_port);
  srv_sock=Util.createServerSocket(new DefaultSocketFactory(), "server", local.getAddress(), local.getPort(), local.getPort());
  System.out.println("Listening on " + srv_sock.getLocalSocketAddress());
  acceptor=new Acceptor();
  acceptor.start();
  sock=new Socket();
  //sock.bind(local);
  sock.setSendBufferSize(SOCK_SEND_BUF_SIZE);
  sock.setReceiveBufferSize(SOCK_RECV_BUF_SIZE);
  try {
    sock.connect(remote);
    output=new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
    System.out.println("Connected to " + sock.getRemoteSocketAddress());
  }
  catch(Throwable t) {
    System.out.println("Failed connecting to " + remote + ": will only act as server");
  }
}

代码示例来源:origin: jenkinsci/jenkins

public boolean connect(Socket socket) throws IOException {
    try {
      LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
      try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
        out.writeUTF("Protocol:Ping");
        try (InputStream in = socket.getInputStream()) {
          byte[] response = new byte[ping.length];
          int responseLength = in.read(response);
          if (responseLength == ping.length && Arrays.equals(response, ping)) {
            LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
            return true;
          } else {
            LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
                socket.getRemoteSocketAddress(),
                new String(ping, "UTF-8"),
                responseLength > 0 && responseLength <= response.length ?
                  new String(response, 0, responseLength, "UTF-8") :
                  "bad response length " + responseLength
            });
            return false;
          }
        }
      }
    } finally {
      socket.close();
    }
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Tell the server to exit
 */
public void sendQuit() 
 throws IOException
{
 Socket socket = new Socket(host, port);
 
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("quit\n");
 out.flush();    
 socket.close();
}

代码示例来源:origin: jenkinsci/jenkins

@Override
public void handle(Socket socket) throws IOException, InterruptedException {
  try {
    try (OutputStream stream = socket.getOutputStream()) {
      LOGGER.log(Level.FINE, "Received ping request from {0}", socket.getRemoteSocketAddress());
      stream.write(ping);
      stream.flush();
      LOGGER.log(Level.FINE, "Sent ping response to {0}", socket.getRemoteSocketAddress());
    }
  } finally {
    socket.close();
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

private Session(Socket socket) throws IOException {
 client = socket;
 in = new BufferedReader(new InputStreamReader(client.getInputStream(), charset));
 out = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), charset));
 start();
}

代码示例来源:origin: apache/zookeeper

public static void kill(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[4];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}

代码示例来源:origin: frohoff/ysoserial

public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException {
    System.err.println("* Opening socket " + isa);
    Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
    s.setKeepAlive(true);
    s.setTcpNoDelay(true);
  
    System.err.println("* Opening channel");
    OutputStream outputStream = s.getOutputStream();
    DataOutputStream dos = new DataOutputStream(outputStream);
    dos.writeUTF("Protocol:CLI-connect");
    ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() {
  
      public Thread newThread ( Runnable r ) {
        Thread t = new Thread(r, "Channel");
        t.setDaemon(true);
        return t;
      }
    });
    Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream);
    System.err.println("* Channel open");
    return c;
  }
}

代码示例来源:origin: wildfly/wildfly

public void init(String local_addr, String remote_addr, int local_port, int remote_port) throws Exception {
  local=new InetSocketAddress(local_addr, local_port);
  remote=new InetSocketAddress(remote_addr, remote_port);
  destination=new IpAddress(remote.getAddress(), remote.getPort());
  srv_sock=Util.createServerSocket(new DefaultSocketFactory(), "server", local.getAddress(), local.getPort());
  System.out.println("Listening on " + srv_sock.getLocalSocketAddress());
  acceptor=new Acceptor();
  acceptor.start();
  sock=new Socket();
  //sock.bind(local);
  sock.setSendBufferSize(SOCK_SEND_BUF_SIZE);
  sock.setReceiveBufferSize(SOCK_RECV_BUF_SIZE);
  try {
    sock.connect(remote);
    output=new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
    System.out.println("Connected to " + sock.getRemoteSocketAddress());
  }
  catch(Throwable t) {
    System.out.println("Failed connecting to " + remote + ": will only act as server");
  }
}

代码示例来源:origin: jenkinsci/jenkins

Writer o = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
  InputStream i = s.getInputStream();
  IOUtils.copy(i, new NullOutputStream());
  s.shutdownInput();
} finally {
  s.close();

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Tokenize the text according to the parser's tokenizer, 
 * return it as whitespace tokenized text.
 */
public String getTokenizedText(String query) 
 throws IOException
{
 Socket socket = new Socket(host, port);
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("tokenize " + query + "\n");
 out.flush();
 String result = readResult(socket);
 socket.close();
 return result;
}

代码示例来源:origin: jMonkeyEngine/jmonkeyengine

public SocketConnector( InetAddress address, int port ) throws IOException
{
  this.sock = new Socket(address, port);
  remoteAddress = sock.getRemoteSocketAddress(); // for info purposes 
  
  // Disable Nagle's buffering so data goes out when we
  // put it there.
  sock.setTcpNoDelay(true);
  
  in = sock.getInputStream();
  out = sock.getOutputStream();
  
  connected.set(true);
}

代码示例来源:origin: apache/storm

@Override
public void prepare(Map<String, Object> topoConf, Object registrationArgument, TopologyContext context, IErrorReporter errorReporter) {
  String[] parts = ((String) registrationArgument).split(":", 2);
  host = parts[0];
  port = Integer.valueOf(parts[1]);
  try {
    socket = new Socket(host, port);
    out = socket.getOutputStream();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: redisson/redisson

public TCPObjectSocket( Socket socket, FSTConfiguration conf) throws IOException {
    this.socket = socket;
//        socket.setSoLinger(true,0);
    this.out = new BufferedOutputStream(socket.getOutputStream(), BUFFER_SIZE);
    this.in  = new BufferedInputStream(socket.getInputStream(), BUFFER_SIZE);
    this.conf = conf;
  }

代码示例来源:origin: plantuml/plantuml

private void retr(final String fileName, Socket soc) throws UnknownHostException, IOException, InterruptedException {
  final OutputStream os = soc.getOutputStream();
  final byte[] data = connexion.getData(fileName);
  if (data != null) {
    os.write(data);
  }
  os.flush();
  os.close();
  soc.close();
  myOut("226 Transfer complete.");
}

相关文章