Java Code Examples for java.nio.channels.SocketChannel#write()

The following examples show how to use java.nio.channels.SocketChannel#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestBlockingNIO.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void client() throws IOException{
    //1. 获取通道
    SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

    FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);

    //2. 分配指定大小的缓冲区
    ByteBuffer buf = ByteBuffer.allocate(1024);

    //3. 读取本地文件,并发送到服务端
    while(inChannel.read(buf) != -1){
        buf.flip();
        sChannel.write(buf);
        buf.clear();
    }

    //4. 关闭通道
    inChannel.close();
    sChannel.close();
}
 
Example 2
Source File: MultiThreadNIOEchoServer.java    From LearningOfThinkInJava with Apache License 2.0 6 votes vote down vote up
private void doWrite(SelectionKey sk){
    SocketChannel channel=(SocketChannel)sk.channel();
    EchoClient echoClient=(EchoClient)sk.attachment();
    LinkedList<ByteBuffer> outq=echoClient.getOutputQueue();

    ByteBuffer bb=outq.getLast();
    try {
        int len=channel.write(bb);
        if(len==-1){
            disconnect(sk);
            return;
        }
        if(bb.remaining()==0){
            outq.removeLast();
        }
    }catch (Exception e){
        e.printStackTrace();
        System.out.println("fail to write to client");
        disconnect(sk);
    }

    if(outq.size()==0){
        sk.interestOps(SelectionKey.OP_READ);
    }

}
 
Example 3
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * @tests SocketChannel#write(ByteBuffer) after close
 */
public void test_socketChannel_write_close() throws Exception {
    // regression 4 for HARMONY-549
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(null);
    SocketChannel sc = SocketChannel.open();
    sc.connect(ssc.socket().getLocalSocketAddress());
    SocketChannel sock = ssc.accept();
    ByteBuffer buf = null;
    ssc.close();
    sc.close();
    try {
        sc.write(buf);
        fail("should throw NPE");
    } catch (NullPointerException expected) {
    }
    sock.close();
}
 
Example 4
Source File: HeapDataOutputStream.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * sends the data from "in" by writing it to "sc" through "out" (out is used
 * to chunk to data and is probably a direct memory buffer).
 */
private final void sendChunkTo(ByteBuffer in, SocketChannel sc, ByteBuffer out) throws IOException {
  int bytesSent = in.remaining();
  final int OUT_MAX = out.capacity();
  out.clear();
  final byte[] bytes = in.array();
  int off = in.arrayOffset() + in.position();
  int len = bytesSent;
  while (len > 0) {
    int bytesThisTime = len;
    if (bytesThisTime > OUT_MAX) {
      bytesThisTime = OUT_MAX;
    }
    out.put(bytes, off, bytesThisTime);
    off += bytesThisTime;
    len -= bytesThisTime;
    out.flip();
    while (out.remaining() > 0) {
      sc.write(out);
    }
    out.clear();
  }
  in.position(in.limit());
  this.size -= bytesSent;
}
 
Example 5
Source File: UnknownHostTcpTest.java    From netcrusher-java with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(true);
    channel.connect(new InetSocketAddress(HOSTNAME_BIND, PORT_CRUSHER));

    try {
        Assert.assertEquals(0, crusher.getClientAddresses().size());
        Thread.sleep(3002);
        Assert.assertEquals(0, crusher.getClientAddresses().size());

        ByteBuffer bb = ByteBuffer.allocate(100);
        bb.put((byte) 0x01);
        bb.flip();

        try {
            channel.write(bb);
            Assert.fail("Exception is expected");
        } catch (IOException e) {
            //
        }
    } finally {
        channel.close();
    }
}
 
Example 6
Source File: TestTunnelWithArbitraryTCPTraffic.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Test(enabled=false, timeOut = 15000)
public void testTunnelToEchoServer() throws IOException {
  MockServer proxyServer = startConnectProxyServer();
  Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
      proxyServer.getServerSocketPort());

  try {
    int tunnelPort = tunnel.getPort();
    SocketChannel client = SocketChannel.open();

    client.connect(new InetSocketAddress("localhost", tunnelPort));
    client.write(ByteBuffer.wrap("Knock\n".getBytes()));
    String response = readFromSocket(client);
    client.close();

    assertEquals(response, "Knock Knock\n");
    assertEquals(proxyServer.getNumConnects(), 1);
  } finally {
    proxyServer.stopServer();
    tunnel.close();
    assertFalse(tunnel.isTunnelThreadAlive());
  }
}
 
Example 7
Source File: NIOClient.java    From spring-boot-demo with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        InetSocketAddress socketAddress = new InetSocketAddress("0.0.0.0", 10002);
        SocketChannel socketChannel = SocketChannel.open(socketAddress);

        log.info("连接 BIOServer 服务,端口:10002...");

        ArrayList<String> companyDetails = new ArrayList<>();

        // 创建消息列表
        companyDetails.add("腾讯");
        companyDetails.add("阿里巴巴");
        companyDetails.add("京东");
        companyDetails.add("百度");
        companyDetails.add("google");

        for (String companyName : companyDetails) {
            socketChannel.write(ByteBuffer.wrap(companyName.getBytes()));
            log.info("发送: " + companyName);

            ByteBuffer buffer = ByteBuffer.allocate(BUFF_SIZE);
            buffer.clear();
            socketChannel.read(buffer);
            String result = new String(buffer.array()).trim();
            log.info("收到NIOServer回复的消息:" + result);

            // 等待2秒钟再发送下一条消息
            Thread.sleep(2000);
        }

        socketChannel.close();
    }
 
Example 8
Source File: ProgMainClientNio.java    From javase with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

	InetSocketAddress myAddr = new InetSocketAddress("127.0.0.1", 8989);
	SocketChannel myClient = SocketChannel.open(myAddr);

	System.out.println("Connecting to Server on port 8989 ...");

	ArrayList<String> companyDetails = new ArrayList<String>();

	// create a ArrayList with companyName list
	companyDetails.add("Facebook");
	companyDetails.add("Twitter");
	companyDetails.add("IBM");
	companyDetails.add("Google");

	for (String companyName : companyDetails) {

		byte[] message = new String(companyName).getBytes();
		ByteBuffer buffer = ByteBuffer.wrap(message);
		myClient.write(buffer);

		System.out.println("sending: " + companyName);
		buffer.clear();
		
		/*
		myClient.read(buffer);
		buffer.flip();
		byte[] data = new byte[buffer.limit()];
		buffer.get(data);
		System.out.println(new String(data));
		buffer.clear();
		
		System.out.println("receiving: " + new String(data));
		*/
		// wait for 2 seconds before sending next message
		Thread.sleep(2000);
	}
	myClient.close();
}
 
Example 9
Source File: TestBlockingNIO2.java    From code with Apache License 2.0 5 votes vote down vote up
@Test
public void client() throws IOException{
	SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

	FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);

	ByteBuffer buf = ByteBuffer.allocate(1024);

	while(inChannel.read(buf) != -1){
		buf.flip();
		sChannel.write(buf);
		buf.clear();
	}

	sChannel.shutdownOutput();

	//接收服务端的反馈
	int len = 0;
	while((len = sChannel.read(buf)) != -1){
		buf.flip();
		System.out.println(new String(buf.array(), 0, len));
		buf.clear();
	}

	inChannel.close();
	sChannel.close();
}
 
Example 10
Source File: RequestReader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void sendException(Exception e) {
  SocketChannel channel = this.socket.getChannel();
  if (channel == null || !channel.isOpen()) {
    throw new IllegalStateException("cannot write to channel");
  }
  try {
    if (e instanceof ClientError) {
      channel.write(charsetASCII.encode(Reply.CLIENT_ERROR.toString()));
    } else {
      channel.write(charsetASCII.encode(Reply.ERROR.toString()));
    }
  } catch (IOException ex) {
  }
}
 
Example 11
Source File: Proxy.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Read all data from <code>from</code> and write it to <code>to</code>.
 * Returns false if channel was closed
 */
boolean relay(SocketChannel from, SocketChannel to, ByteBuffer buf) throws Exception {
    int num;
    StringBuffer sb;

    buf.clear();
    while (true) {
        num=from.read(buf);
        if (num < 0)
            return false;
        else
            if (num == 0)
                return true;
        buf.flip();
        if (verbose) {
            log(printRelayedData(toString(from), toString(to), buf.remaining()));
        }
        if (debug) {
            sb=new StringBuffer();
            sb.append(new String(buf.array()).trim());
            sb.append('\n');
            log(sb.toString());
        }
        to.write(buf);
        buf.flip();
    }
}
 
Example 12
Source File: EchoServer.java    From netty.book.kor with MIT License 5 votes vote down vote up
/**
 * Called when a SelectionKey is ready for writing.
 */
private void doWrite(SelectionKey sk) {
    SocketChannel channel = (SocketChannel) sk.channel();
    EchoClient echoClient = (EchoClient) sk.attachment();
    LinkedList<ByteBuffer> outq = echoClient.getOutputQueue();

    ByteBuffer bb = outq.getLast();
    try {
        int len = channel.write(bb);
        if (len == -1) {
            disconnect(sk);
            return;
        }

        if (bb.remaining() == 0) {
            // The buffer was completely written, remove it.
            outq.removeLast();
        }
    }
    catch (Exception e) {
        System.out.println("Failed to write to client.");
        e.printStackTrace();
    }

    // If there is no more data to be written, remove interest in
    // OP_WRITE.
    if (outq.size() == 0) {
        sk.interestOps(SelectionKey.OP_READ);
    }
}
 
Example 13
Source File: TestBlockingNIO2.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void client() throws IOException {
    SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

    FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);

    ByteBuffer buf = ByteBuffer.allocate(1024);

    while (inChannel.read(buf) != -1) {
        buf.flip();
        sChannel.write(buf);
        buf.clear();
    }

    sChannel.shutdownOutput();

    // 接收服务端的反馈
    int len = 0;
    while ((len = sChannel.read(buf)) != -1) {
        buf.flip();
        System.out.println(new String(buf.array(), 0, len));
        buf.clear();
    }

    inChannel.close();
    sChannel.close();
}
 
Example 14
Source File: SocketChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
 */
public void test_write$LByteBuffer_writes() throws IOException {
    // Set-up
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(null);
    SocketChannel client = SocketChannel.open();
    client.connect(server.socket().getLocalSocketAddress());
    SocketChannel worker = server.accept();

    // Data to write
    byte[] data = "Hello world!".getBytes("UTF-8");
    ByteBuffer[] buffers = new ByteBuffer[3];
    buffers[0] = ByteBuffer.wrap(data, 0, 6);
    buffers[1] = ByteBuffer.wrap("world!".getBytes("UTF-8"));
    buffers[2] = buffers[0];
    assertTrue(buffers[0].hasArray());

    // Test a sequence of write calls
    client.write(buffers, 0, 0); // write nothing
    client.write(buffers, 1, 0); // write nothing
    client.write(buffers, 0, 1); // write "Hello "
    assertEquals("Failed to drain buffer 0", 0, buffers[0].remaining());
    assertEquals("Shouldn't touch buffer 1", buffers[1].limit(), buffers[1]
            .remaining());
    client.write(buffers, 0, 2); // writes "world!"
    assertEquals("Failed to drain buffer 1", 0, buffers[1].remaining());
    client.write(buffers, 0, 3); // write nothing
    client.close();

    // Read what we wrote and check it
    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    while (EOF != worker.read(readBuffer)) {}
    readBuffer.flip();
    assertEquals(ByteBuffer.wrap(data), readBuffer);

    // Tidy-up
    worker.close();
    server.close();
}
 
Example 15
Source File: MultiplexerTimeServer.java    From JavaInterview with Apache License 2.0 5 votes vote down vote up
private void doWrite(SocketChannel sc, String respone) throws IOException {
    if (respone != null && respone.trim().length() > 0){
        byte[] respArr = respone.getBytes();
        ByteBuffer buf = ByteBuffer.allocate(respArr.length);
        buf.put(respArr);
        buf.flip();
        sc.write(buf);
    }
}
 
Example 16
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	try {
		server.configureBlocking(true);
		server.socket()
		      .bind(new InetSocketAddress(port));
		countDown();
		thread = Thread.currentThread();
		while (true) {
			SocketChannel ch = server.accept();

			ByteBuffer buffer = ByteBuffer.allocate(8192);
			while (true) {
				int read = ch.read(buffer);
				if (read > 0) {
					buffer.flip();
				}

				int written = ch.write(buffer);
				if (written < 0) {
					throw new IOException("Cannot write to client");
				}
				buffer.rewind();
			}
		}
	}
	catch (IOException e) {
		// Server closed
	}
}
 
Example 17
Source File: PyroClient.java    From TelegramApi with MIT License 5 votes vote down vote up
private int onReadyToWrite(long now) throws IOException
{
   this.selector.checkThread();
   //this.lastEventTime = now;

   int sent = 0;

   // copy outbound bytes into network buffer
   ByteBuffer buffer = this.selector.networkBuffer;
   buffer.clear();
   this.outbound.get(buffer);
   buffer.flip();

   // write to channel
   if (buffer.hasRemaining())
   {
      SocketChannel channel = (SocketChannel) key.channel();
      sent = channel.write(buffer);
   }

   if (sent > 0)
   {
      this.outbound.discard(sent);
   }

   for (PyroClientListener listener : this.listeners)
      listener.sentData(this, sent);

   this.adjustWriteOp();

   if (this.doShutdown && !this.outbound.hasData())
   {
      this.dropConnection();
   }

   return sent;
}
 
Example 18
Source File: HTTPWriteHandler.java    From AdditionsAPI with MIT License 5 votes vote down vote up
private void writeBuffer(SocketChannel channel, HTTPResponse response) throws IOException
{
	int byteRead = channel.write(response.buffer);
	
	if(byteRead == -1)
	{
		throw new IOException("End of Stream");
	}
}
 
Example 19
Source File: AbstractBenchmarkClient.java    From artio with Apache License 2.0 5 votes vote down vote up
protected void write(final SocketChannel socketChannel, final long result) throws IOException
{
    final int offset = Encoder.offset(result);
    final int length = Encoder.length(result);

    ByteBufferUtil.position(writeBuffer, offset);
    ByteBufferUtil.limit(writeBuffer, offset + length);
    int remaining = length;
    do
    {
        remaining -= socketChannel.write(writeBuffer);
    }
    while (remaining > 0);
    // System.out.println(writeFlyweight.getAscii(0, amount));
}
 
Example 20
Source File: TCPSender.java    From fluency with Apache License 2.0 4 votes vote down vote up
@Override
protected void sendBuffers(SocketChannel socketChannel, List<ByteBuffer> buffers)
        throws IOException
{
    socketChannel.write(buffers.toArray(new ByteBuffer[0]));
}