本文整理匯總了Java中java.nio.channels.SocketChannel.read方法的典型用法代碼示例。如果您正苦於以下問題:Java SocketChannel.read方法的具體用法?Java SocketChannel.read怎麽用?Java SocketChannel.read使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.nio.channels.SocketChannel
的用法示例。
在下文中一共展示了SocketChannel.read方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: call
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public ByteBuffer call() throws Exception {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
buff = ByteBuffer.allocate(bufferSize);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
RandomAccessFile temp = new RandomAccessFile(tempName, "rw");
MappedByteBuffer b;
while (!stop.isLocked()) {
sync=0;
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.read(buff);
FileChannel channel = temp.getChannel();
channel.write(buff);
if (!pause.isLocked()) {
b = channel.map(MapMode.READ_WRITE, 0, (long) bufferSize);
sync = 1;
if(sync==2){
b.clear();
}
}
buff.clear();
}
temp.close();
return null;
}
示例2: run
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(Options.getInstance().bufferSize);
while (running) {
try {
selector.select();
Set selectedKeys = selector.selectedKeys();
for (Object selectedKey : selectedKeys) {
SelectionKey key = (SelectionKey) selectedKey;
SocketChannel channel = (SocketChannel) key.channel();
channel.read(buffer);
//TODO
}
} catch (IOException e) {
Lg.e(Error.READER, e);
}
}
}
示例3: readData
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void readData() throws Exception {
buff.clear();
SocketChannel sc = (SocketChannel) sk.channel();
int count = -1;
while ((count = sc.read(buff)) > 0) {
// TODO - in the future pass this to a "listener" which will do something useful with this buffer
buff.clear();
}
if (count < 0) {
sc.close();
} else {
sk.interestOps(sk.interestOps() | SelectionKey.OP_READ);
}
sel.wakeup();
}
示例4: 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);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data.array()));
Object obj = ois.readObject();
if (!isReady() && !(obj instanceof PublicKey))
return;
if (obj instanceof PublicKey) {
setPublicKey((PublicKey) obj);
return;
}
if (!(obj instanceof MeviusPacket))
return;
MeviusPacket packet = (MeviusPacket) obj;
handler.callEvent(MeviusHandler.getPacketEventInstance(packet,
handler.getClientHandler().getClient(channel.socket().getInetAddress().getHostAddress()),
PacketEventType.RECEIVE));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
if (e.getClass().equals(StreamCorruptedException.class))
try {
disconnect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
示例5: read
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(4096);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int bytesRead;
try {
bytesRead = channel.read(buffer);
} 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 (bytesRead == -1) {
key.cancel();
channel.close();
if (this.rconSessions.contains(channel)) {
this.rconSessions.remove(channel);
}
if (this.sendQueues.containsKey(channel)) {
this.sendQueues.remove(channel);
}
return;
}
buffer.flip();
this.handle(channel, new RCONPacket(buffer));
}
示例6: transferData
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public void transferData(SelectionKey key) {
SocketChannel activeSocket = (SocketChannel) key.channel();
SocketChannel passiveSocket = bridge.get(activeSocket);
try {
// throws when closed
activeSocket.read(buffer);
byte[] bytes = new byte[buffer.position()];
if (buffer.position() == 0) {
// end of stream
doRecycle(activeSocket, passiveSocket, key);
return;
} else {
System.arraycopy(buffer.array(), 0, bytes, 0, bytes.length);
}
buffer.flip();
if (activeSocket.socket().getLocalSocketAddress() == srcAddr) {
passiveSocket.write(buffer);
} else {
passiveSocket.write(buffer);
}
buffer.clear();
} catch (Exception e) {
doRecycle(activeSocket, passiveSocket, key);
} finally {
buffer.clear();
}
}
示例7: read
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void read(SocketChannel channel) throws Exception {
LinkedList<Byte> list = new LinkedList<>();
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buf);
// 如果讀取到-1,則說明客戶端關閉了該鏈接
if (bytesRead == -1) {
log.info("Close channel {}", channel.getRemoteAddress());
channel.close();
return;
}
// 非阻塞IO可以讀取0個字節,這種數據應該手動丟棄
if (bytesRead == 0) return;
// 讀取所有的數據
while (bytesRead > 0) {
buf.flip();
while (buf.hasRemaining()) {
list.add(buf.get());
}
buf.clear();
bytesRead = channel.read(buf);
}
String request = new String(Bytes.toArray(list), Constants.DEFAULT_ENCODING);
try {
// 寫回響應
response(request, channel);
} catch (Exception e) {
e.printStackTrace();
// 返回錯誤信息
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
serverError(stringWriter.toString(), channel);
}
}
示例8: handRead
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void handRead(SelectionKey key) throws IOException {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); // 1k
sc.read(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
key.interestOps(SelectionKey.OP_WRITE);
System.out.println("server read");
System.out.println(new String(data, "UTF-8"));
}
示例9: read
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void read(SelectionKey key) throws Exception {
// 服務器可讀消息,得到事件發生的socket通道
SocketChannel channel = (SocketChannel) key.channel();
// 穿件讀取的緩衝區
ByteBuffer buffer = ByteBuffer.allocate(10);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("server receive from client: " + msg);
ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
channel.write(outBuffer);
}
示例10: read
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void read(SelectionKey key) throws Exception {
SocketChannel channel = (SocketChannel) key.channel();
// 穿件讀取的緩衝區
ByteBuffer buffer = ByteBuffer.allocate(10);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("client receive msg from server:" + msg);
ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
channel.write(outBuffer);
}
示例11: handRead
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void handRead(SelectionKey key) throws IOException {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); // 1K
sc.read(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
key.interestOps(SelectionKey.OP_WRITE);
System.out.println("client read");
System.out.println(new String(data, "UTF-8"));
}
示例12: read
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
// 創建讀取的緩衝區
ByteBuffer buffer = ByteBuffer.allocate(100);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("客戶端收到信息:" + msg);
channel.close();
key.selector().close();
}
示例13: start
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
@SuppressWarnings("InfiniteLoopStatement")
public void start() throws Exception {
try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
serverSocketChannel.bind(new InetSocketAddress("localhost", PORT));
serverSocketChannel.configureBlocking(false); //non blocking mode
int ops = SelectionKey.OP_ACCEPT;
Selector selector = Selector.open();
serverSocketChannel.register(selector, ops, null);
logger.info("Started on port: " + PORT);
while (true) {
selector.select();//blocks
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
try {
if (key.isAcceptable()) {
SocketChannel client = serverSocketChannel.accept(); //non blocking accept
System.out.println("Connection Accepted: " + client.getLocalAddress());
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(CAPACITY);
int read = channel.read(buffer);
if (read != -1) {
String result = new String(buffer.array()).trim();
if (!result.isEmpty())
System.out.println("Message received: " + result + " from: " + channel.getRemoteAddress());
} else {
key.cancel();
System.out.println("Connection closed, key canceled");
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, e.getMessage());
} finally {
iterator.remove();
}
}
}
}
}
示例14: processInput
import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void processInput(SelectionKey key, Iterator<SelectionKey> keyIterator)
{
keyIterator.remove();
ByteBuffer receiveBuffer = ByteBufferPool.acquire();
// Leave space for the header
receiveBuffer.position(HEADER_SIZE);
TCB tcb = (TCB) key.attachment();
synchronized (tcb)
{
Packet referencePacket = tcb.referencePacket;
SocketChannel inputChannel = (SocketChannel) key.channel();
int readBytes;
try
{
readBytes = inputChannel.read(receiveBuffer);
}
catch (IOException e)
{
Log.e(TAG, "Network read error: " + tcb.ipAndPort, e);
referencePacket.updateTCPBuffer(receiveBuffer, (byte) Packet.TCPHeader.RST, 0, tcb.myAcknowledgementNum, 0);
outputQueue.offer(receiveBuffer);
TCB.closeTCB(tcb);
return;
}
if (readBytes == -1)
{
// End of stream, stop waiting until we push more data
key.interestOps(0);
tcb.waitingForNetworkData = false;
if (tcb.status != TCB.TCBStatus.CLOSE_WAIT)
{
ByteBufferPool.release(receiveBuffer);
return;
}
tcb.status = TCB.TCBStatus.LAST_ACK;
referencePacket.updateTCPBuffer(receiveBuffer, (byte) Packet.TCPHeader.FIN, tcb.mySequenceNum, tcb.myAcknowledgementNum, 0);
tcb.mySequenceNum++; // FIN counts as a byte
}
else
{
// XXX: We should ideally be splitting segments by MTU/MSS, but this seems to work without
referencePacket.updateTCPBuffer(receiveBuffer, (byte) (Packet.TCPHeader.PSH | Packet.TCPHeader.ACK),
tcb.mySequenceNum, tcb.myAcknowledgementNum, readBytes);
tcb.mySequenceNum += readBytes; // Next sequence number
receiveBuffer.position(HEADER_SIZE + readBytes);
}
}
outputQueue.offer(receiveBuffer);
}
示例15: 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");
}
}