本文整理汇总了Java中java.nio.channels.SocketChannel.write方法的典型用法代码示例。如果您正苦于以下问题:Java SocketChannel.write方法的具体用法?Java SocketChannel.write怎么用?Java SocketChannel.write使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.nio.channels.SocketChannel
的用法示例。
在下文中一共展示了SocketChannel.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: write
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public int
write(
SocketChannel chan,
ByteBuffer buffer )
throws IOException
{
int pos = buffer.position();
int len = chan.write( buffer );
if ( len > 0 ){
buffer.position( pos );
analyse( buffer, len );
}
return( len );
}
示例2: write
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void write(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
synchronized (this.sendQueues) {
List<RCONPacket> queue = this.sendQueues.get(channel);
ByteBuffer buffer = queue.get(0).toBuffer();
try {
channel.write(buffer);
queue.remove(0);
} catch (IOException exception) {
key.cancel();
channel.close();
if (this.rconSessions.contains(channel)) {
this.rconSessions.remove(channel);
}
if (this.sendQueues.containsKey(channel)) {
this.sendQueues.remove(channel);
}
return;
}
if (queue.isEmpty()) {
this.sendQueues.remove(channel);
}
key.interestOps(SelectionKey.OP_READ);
}
}
示例3: read
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void read(SelectionKey k) {
try {
SocketChannel channel = (SocketChannel) k.channel();
ByteBuffer data = ByteBuffer.allocate(100000);
data.clear();
channel.read(data);
ByteArrayInputStream bais = new ByteArrayInputStream(data.array());
ObjectInputStream ois = new ObjectInputStream(bais);
Object obj = ois.readObject();
MeviusClient client = handler.getClientHandler()
.getClient(channel.socket().getInetAddress().getHostAddress());
if (obj instanceof PublicKey) {
handler.getClientHandler().setPublicKey(client, ((PublicKey) obj));
channel.write(convert(keypair.getPublic()));
return;
}
if (!(obj instanceof MeviusPacket))
return;
MeviusPacket packet = (MeviusPacket) obj;
handler.callEvent(MeviusHandler.getPacketEventInstance(packet, client, PacketEventType.RECEIVE));
} catch (IOException | ClassNotFoundException e) {
if (e.getClass().equals(StreamCorruptedException.class)) {
k.cancel();
MeviusClient mc = handler.getClientHandler()
.getClient(((SocketChannel) k.channel()).socket().getInetAddress().getHostAddress());
try {
mc.disconnect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return;
}
k.cancel();
e.printStackTrace();
}
}
示例4: send
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/**
* 把sendBuffer中的数据发送给Server,然后删除已发送的数据
* @param key
* @throws IOException
*/
private void send(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (sendBuffer){
sendBuffer.flip();//把极限设置为位置,把位置设置为0
socketChannel.write(sendBuffer);//发送数据
sendBuffer.compact();//删除已经发送的数据
}
}
示例5: doIt
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private static void doIt(SocketChannel sc, int closeAfter, int delay) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(1024);
int total = 0;
for (;;) {
bb.clear();
int n = sc.read(bb);
if (n < 0) {
break;
}
total += n;
// echo
bb.flip();
sc.write(bb);
// close after X bytes?
if (closeAfter > 0 && total >= closeAfter) {
break;
}
}
sc.close();
if (delay > 0) {
try {
Thread.currentThread().sleep(delay);
} catch (InterruptedException x) { }
}
}
示例6: writeResponse
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void writeResponse(SocketChannel channel, List<String> response)
throws IOException
{
String s = response.stream().collect(Collectors.joining("\r\n"))
+ "\r\n\r\n";
ByteBuffer encoded;
try {
encoded = ISO_8859_1.newEncoder().encode(CharBuffer.wrap(s));
} catch (CharacterCodingException e) {
throw new UncheckedIOException(e);
}
while (encoded.hasRemaining()) {
channel.write(encoded);
}
}
示例7: sendMessage
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void sendMessage(SocketChannel socketChannel, ByteBuffer message) {
message.flip();
try {
socketChannel.write(message);
} catch (IOException e) {
e.printStackTrace();
}
}
示例8: listen
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/**
* * // 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 * @throws // IOException
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void listen() throws Exception { // 轮询访问selector
while (true) {
// 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
// 这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
// selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
selector.select(); // 获得selector中选中的项的迭代器
Iterator ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next(); // 删除已选的key,以防重复处理
ite.remove(); // 连接事件发生
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key.channel(); // 如果正在连接,则完成连接
if (channel.isConnectionPending()) {
channel.finishConnect();
} // 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以给服务端发送信息哦
channel.write(ByteBuffer.wrap(new String("hello server!").getBytes()));
// 在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ); // 获得了可读的事件
} else if (key.isReadable()) {
read(key);
}
}
}
}
示例9: run
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public void run() {
SocketChannel sChannel = null;
try {
/*
* For future unwary socket programmers: although connect 'blocks' it
* does not require an accept on the server side to return. Therefore
* you can not assume that all the sockets are connected at the end of
* this for loop.
*/
sChannel = SocketChannel.open();
sChannel.connect(new InetSocketAddress(host,port));
// Construct a connection request
ConnectRequest conReq = new ConnectRequest(0, 0,
10000, 0, "password".getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
boa.writeInt(-1, "len");
conReq.serialize(boa, "connect");
baos.close();
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
bb.putInt(bb.capacity() - 4);
bb.rewind();
/* Send a connect request. Any socket that has been closed (or at least
* not added to the cnxn list on the server) will not have any bytes to
* read and get an eof.
*
* The trick here was finding a call that caused the server to put
* bytes in the input stream without closing the cnxn. None of
* the four letter commands do that, so we actually try to create
* a session which should send us something back, while maintaining
* the connection.
*/
int eof = sChannel.write(bb);
// If the socket times out, we count that as Assert.failed -
// the server should respond within 10s
sChannel.socket().setSoTimeout(10000);
if (!sChannel.socket().isClosed()){
eof = sChannel.socket().getInputStream().read();
if (eof != -1) {
numConnected.incrementAndGet();
}
}
}
catch (IOException io) {
// "Connection reset by peer"
} finally {
if (sChannel != null) {
try {
sChannel.close();
} catch (Exception e) {
// Do nothing
}
}
}
}
示例10: main
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void main(String args[]) throws Exception {
String msg = "HELLO";
// Launch the service with arguments to tell it to close
// the connection after reading 5 bytes ("HELLO"). After
// closing the connection the service should hang around
// for 15 seconds.
String service_args[] = new String[2];
service_args[0] = String.valueOf(msg.length());
service_args[1] = String.valueOf( 15*1000 );
SocketChannel sc = Launcher.launchWithSocketChannel("EchoService", service_args);
// send message - service will echo the message and close the connection.
sc.write(ByteBuffer.wrap(msg.getBytes("UTF-8")));
// read the reply (with timeout)
ByteBuffer bb = ByteBuffer.allocateDirect(50);
sc.configureBlocking(false);
Selector sel = sc.provider().openSelector();
SelectionKey sk = sc.register(sel, SelectionKey.OP_READ);
long to = 12 * 1000;
for (;;) {
long st = System.currentTimeMillis();
sel.select(to);
if (sk.isReadable()) {
int n = sc.read(bb);
// EOF
if (n < 0) {
break;
}
}
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0) {
throw new RuntimeException("Timed out waiting for connection to close");
}
}
sel.close();
sc.close();
// finally check that the reply length is okay
bb.flip();
if (bb.remaining() < msg.length()) {
throw new RuntimeException("Premature EOF from echo service");
}
System.out.println("Test passed - service closed connection.");
}
示例11: notifyWritable
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
void notifyWritable() throws IOException {
if (_responseBuffer == null) {
return;
}
final SocketChannel socketChannel = _socketChannel;
socketChannel.write(_responseBuffer);
if (!_responseBuffer.hasRemaining()) {
if (_response.hasUserBodyStream()) {
final Selector selector = _server._selector;
final XulHttpServerHandler attachment = this;
socketChannel.register(selector, 0, attachment);
selector.wakeup();
_server._reactorPool.execute(new Runnable() {
@Override
public void run() {
try {
int beginOffset = _sendChunkedData ? 32 : 0;
int endOffset = _sendChunkedData ? 2 : 0;
int sizeLimit = _sendChunkedData ? 8192 : -1;
if (_response == null || !_response.prepareUserBodyData(beginOffset, endOffset, sizeLimit)) {
terminate();
return;
}
int dataSize = _response.getDataSize();
if (dataSize <= 0) {
if (_sendChunkedData) {
_response.writeStream(null);
_responseBuffer = ByteBuffer.wrap("0\r\n\r\n".getBytes());
} else {
terminate();
return;
}
} else {
final byte[] data = _response.getData();
if (_sendChunkedData) {
String dataLength = String.format("%X\r\n", dataSize);
final byte[] dataLengthBytes = dataLength.getBytes();
beginOffset -= dataLengthBytes.length;
System.arraycopy(dataLengthBytes, 0, data, beginOffset, dataLengthBytes.length);
dataSize += dataLengthBytes.length;
data[beginOffset + dataSize++] = '\r';
data[beginOffset + dataSize++] = '\n';
}
_responseBuffer = ByteBuffer.wrap(data, beginOffset, dataSize);
}
socketChannel.register(selector, SelectionKey.OP_WRITE, attachment);
selector.wakeup();
} catch (Exception e) {
terminate();
XulLog.e(TAG, e);
}
}
});
} else {
socketChannel.close();
}
return;
}
}
示例12: TCPEchoTest
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private static void TCPEchoTest() throws IOException {
SocketChannel sc = Launcher.launchWithSocketChannel(ECHO_SERVICE, null);
String msg = "Where's that damn torpedo?";
int repeat = 100;
int size = msg.length() * repeat;
// generate bytes into a buffer and send it to the service
ByteBuffer bb1 = ByteBuffer.allocate(size);
Random gen = new Random();
for (int i=0; i<repeat; i++) {
bb1.put(msg.getBytes("UTF-8"));
}
bb1.flip();
sc.write(bb1);
// now we put the channel into non-blocking mode and we read the
// reply from the service into a second buffer.
ByteBuffer bb2 = ByteBuffer.allocate(size+100);
sc.configureBlocking(false);
Selector sel = sc.provider().openSelector();
SelectionKey sk = sc.register(sel, SelectionKey.OP_READ);
int nread = 0;
long to = 5000;
while (nread < size) {
long st = System.currentTimeMillis();
sel.select(to);
if (sk.isReadable()) {
int n = sc.read(bb2);
if (n > 0) {
nread += n;
}
if (n < 0) {
break; // EOF
}
}
sel.selectedKeys().remove(sk);
to -= System.currentTimeMillis() - st;
if (to <= 0) {
break;
}
}
sc.close();
// and compare the response
boolean err = false;
if (nread != size) {
err = true;
} else {
bb1.flip();
bb2.flip();
while (bb1.hasRemaining()) {
if (bb1.get() != bb2.get()) {
err = true;
}
}
}
// if error print out the response from the service (could be a stack trace)
if (err) {
System.err.println("Bad response or premature EOF, bytes read: ");
bb2.flip();
while (bb2.hasRemaining()) {
char c = (char)bb2.get();
System.out.print(c);
}
throw new RuntimeException("Bad response or premature EOF from service");
}
}
示例13: testCnxManagerSpinLock
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/**
* Tests a bug in QuorumCnxManager that causes a spin lock
* when a negative value is sent. This test checks if the
* connection is being closed upon a message with negative
* length.
*
* @throws Exception
*/
@Test
public void testCnxManagerSpinLock() throws Exception {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2);
QuorumCnxManager cnxManager = new QuorumCnxManager(peer);
QuorumCnxManager.Listener listener = cnxManager.listener;
if(listener != null){
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
}
int port = peers.get(peer.getId()).electionAddr.getPort();
LOG.info("Election port: " + port);
InetSocketAddress addr = new InetSocketAddress(port);
Thread.sleep(1000);
SocketChannel sc = SocketChannel.open();
sc.socket().connect(peers.get(new Long(1)).electionAddr, 5000);
/*
* Write id first then negative length.
*/
byte[] msgBytes = new byte[8];
ByteBuffer msgBuffer = ByteBuffer.wrap(msgBytes);
msgBuffer.putLong(new Long(2));
msgBuffer.position(0);
sc.write(msgBuffer);
msgBuffer = ByteBuffer.wrap(new byte[4]);
msgBuffer.putInt(-20);
msgBuffer.position(0);
sc.write(msgBuffer);
Thread.sleep(1000);
try{
/*
* Write a number of times until it
* detects that the socket is broken.
*/
for(int i = 0; i < 100; i++){
msgBuffer.position(0);
sc.write(msgBuffer);
}
Assert.fail("Socket has not been closed");
} catch (Exception e) {
LOG.info("Socket has been closed as expected");
}
peer.shutdown();
cnxManager.halt();
}
示例14: testCnxManagerSpinLock
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/**
* Tests a bug in QuorumCnxManager that causes a spin lock
* when a negative value is sent. This test checks if the
* connection is being closed upon a message with negative
* length.
*
* @throws Exception
*/
@Test
public void testCnxManagerSpinLock() throws Exception {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
if(listener != null){
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
}
int port = peers.get(peer.getId()).electionAddr.getPort();
LOG.info("Election port: " + port);
InetSocketAddress addr = new InetSocketAddress(port);
Thread.sleep(1000);
SocketChannel sc = SocketChannel.open();
sc.socket().connect(peers.get(new Long(1)).electionAddr, 5000);
/*
* Write id first then negative length.
*/
byte[] msgBytes = new byte[8];
ByteBuffer msgBuffer = ByteBuffer.wrap(msgBytes);
msgBuffer.putLong(new Long(2));
msgBuffer.position(0);
sc.write(msgBuffer);
msgBuffer = ByteBuffer.wrap(new byte[4]);
msgBuffer.putInt(-20);
msgBuffer.position(0);
sc.write(msgBuffer);
Thread.sleep(1000);
try{
/*
* Write a number of times until it
* detects that the socket is broken.
*/
for(int i = 0; i < 100; i++){
msgBuffer.position(0);
sc.write(msgBuffer);
}
Assert.fail("Socket has not been closed");
} catch (Exception e) {
LOG.info("Socket has been closed as expected");
}
peer.shutdown();
cnxManager.halt();
}
示例15: handleWrite
import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void handleWrite(SelectionKey key) throws IOException{//准备写
ByteBuffer buf = (ByteBuffer)key.attachment();
buf.flip();
SocketChannel sc = (SocketChannel) key.channel();
while(buf.hasRemaining()){
sc.write(buf);
}
buf.compact();
}