導航:首頁 > 編程語言 > javanio網路編程

javanio網路編程

發布時間:2022-09-01 17:02:50

java網路編程中怎樣用管道流

一起學習,管道流滿搞的,用著比socket的stream麻煩
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.nio.channels.*;
import java.nio.*;
import java.util.*;
import java.nio.charset.*;
public class TCP extends Thread{
private SocketChannel channel;
private ServerSocket serverSocket;
private ServerSocketChannel serverSocketChannel;
private ByteBuffer readBuffer;
private ByteBuffer sendBuffer;
private Boolean isAccept=false;
private boolean isConnect=false;
private Thread accept;
private Thread connect;
/** Creates a new instance of TCP */
public TCP(int port,String addr) {
try {
readBuffer=ByteBuffer.allocate(1024);
serverSocketChannel=ServerSocketChannel.open();
serverSocket=serverSocketChannel.socket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(port));
channel=SocketChannel.open();
channel.connect(new InetSocketAddress(InetAddress.getByName(addr),port));
accept=new Thread(){
public void run(){
Selector selector;
try {
selector=Selector.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
isAccept=false;
selectors(selector);
} catch (ClosedChannelException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
};
connect=new Thread(){
public void run(){
try{
Selector selector;
selector=Selector.open();
channel.configureBlocking(false);
channel.register(selector,SelectionKey.OP_WRITE|SelectionKey.OP_READ);
isConnect=false;
selectors(selector);
}catch (Exception ex){
ex.printStackTrace();
}
}
};
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("d1");
}catch(Exception ex){
System.out.println("d2");
}
}
private void service(){
if(isConnect){
connect.start();
}
if(isAccept){
accept.start();
}
}
private void selectors(Selector selector){
try {
while (selector.select()>0){
Set readyKeys=selector.selectedKeys();
Iterator<SelectionKey> it=readyKeys.iterator();
while(it.hasNext()){
SelectionKey key=null;
key=it.next();
it.remove();
if(key.isAcceptable()){
//System.out.println("isAcceptable");
ServerSocketChannel ssc=(ServerSocketChannel)key.channel();
SocketChannel socketChannel=ssc.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
}
if(key.isReadable()){
synchronized(readBuffer){
// System.out.println("isReadable");
ByteBuffer buffer=ByteBuffer.allocate(1024);
SocketChannel socketChannel=(SocketChannel)key.channel();
socketChannel.read(buffer);
readBuffer=buffer;
}
}
if(key.isWritable()){
synchronized(sendBuffer){
// System.out.println("isWritable");
SocketChannel channel=(SocketChannel)key.channel();
if(sendBuffer!=null)
channel.write(sendBuffer);
}
}

}
try {
sleep(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} catch (ClosedChannelException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public void send(ByteBuffer buff){
this.sendBuffer=buff;
}
public ByteBuffer get(){
return readBuffer;
}
public void accpet(){
isAccept=true;
}
public void connect(){
isConnect=true;
}
public void run(){
while (true){
service();
}
}
}

Ⅱ 求java nio網路編程的小例子,要求客戶端一直與伺服器保持連接

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import java.io.*;

public class chatClient extends Frame {

/**
* @param args
*/
TextField tfTxT=new TextField();
TextArea taContent=new TextArea();
Socket s=null;
DataOutputStream dos=null;
DataInputStream dis=null;
private boolean bConnected =false;

public static void main(String[] args) {
new chatClient().lunachFrame();
}

private class RecvThread implements Runnable{

public void run() {
try{
while(bConnected){
String str=dis.readUTF();
taContent.setText(taContent.getText()+str+'\n');
}
}catch(IOException e){
e.printStackTrace();
}
}

}

public void lunachFrame(){
this.setLocation(400, 300);
this.setSize(300,300);
//this.setLayout(new FlowLayout());
this.add(tfTxT,"South");
this.add(taContent,"North");
pack();
tfTxT.addActionListener(new TFListener());
this.addWindowListener(new WindowClose());
this.setVisible(true);
connect();
new Thread(new RecvThread()).start();
}

public void connect(){
try {
s= new Socket("127.0.0.1",8888);
dos =new DataOutputStream(s.getOutputStream());
dis =new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected=true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void disconnect(){
try {
dos.close();
s.close();
} catch (Exception e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}

class WindowClose extends WindowAdapter{

@Override
public void windowClosing(WindowEvent e) {
// TODO 自動生成方法存根
System.exit(0);
disconnect();
}

}

private class TFListener implements ActionListener{

public void actionPerformed(ActionEvent e) {
String str=tfTxT.getText().trim();//trim去掉兩邊空格
//taContent.setText(str);
tfTxT.setText("");
try {
dos.writeUTF(str);
dos.flush();
//dos.close();

} catch (IOException e1) {
e1.printStackTrace();

}
}
}
}

======================================
import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer {
List<Client> clients=new ArrayList<Client>();
Client c=null;

public static void main(String[] args){
new ChatServer().start();
}

public void start(){
boolean started=false;
ServerSocket ss=null;
DataInputStream dis=null;
try{
ss=new ServerSocket(8888);
started =true;
}catch(Exception e)
{
e.printStackTrace();
}
try{
while(started){
Socket s=ss.accept();
c=new Client(s);//啟動線程,實行run()方法
System.out.println("a client connected!");
new Thread(c).start();//啟動start方法,循環.start是Thread中的方法與這上面的start無關
clients.add(c);
//dis.close();
}
} catch (Exception e) {

//e.printStackTrace();
}
finally{
try {
ss.close();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
}

class Client implements Runnable{

private Socket s;
private DataInputStream dis =null;
private boolean bConnected =false;
private DataOutputStream dos=null;

public Client(Socket s){
this.s=s;
try {
dis=new DataInputStream(s.getInputStream());
dos =new DataOutputStream(s.getOutputStream());
bConnected =true;
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}

public void send(String str)throws Exception{
dos.writeUTF(str);

}

public void run() {
try{
while(bConnected){
String str = dis.readUTF();
System.out.println(str);
for(int i=0;i<clients.size();i++){
c=clients.get(i);
c.send(str);
}
/*for(Iterator<Client> it=clients.iterator();it.hasNext();){
Client c=it.next();
c.send(str);
}*/
}
}catch(SocketException e){
clients.remove(this);
System.out.println("客戶下線了");
}
catch(EOFException e){
System.out.println("Client closed");
}
catch (Exception e){

//e.printStackTrace();
}
finally{
try {
if(dis !=null) dis.close();
if(dos !=null) dos.close();
if(s!=null) s.close();
} catch (Exception e1) {
// TODO 自動生成 catch 塊
//e1.printStackTrace();
}
}
}
}

}

第一個是客戶端,
第二個是server端

Ⅲ java Nio讀寫為什麼是雙向

作者:美團技術團隊
鏈接:https://zhuanlan.hu.com/p/23488863
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。

NIO(Non-blocking I/O,在Java領域,也稱為New I/O),是一種同步非阻塞的I/O模型,也是I/O多路復用的基礎,已經被越來越多地應用到大型應用伺服器,成為解決高並發與大量連接、I/O處理問題的有效方式。

那麼NIO的本質是什麼樣的呢?它是怎樣與事件模型結合來解放線程、提高系統吞吐的呢?

本文會從傳統的阻塞I/O和線程池模型面臨的問題講起,然後對比幾種常見I/O模型,一步步分析NIO怎麼利用事件模型處理I/O,解決線程池瓶頸處理海量連接,包括利用面向事件的方式編寫服務端/客戶端程序。最後延展到一些高級主題,如Reactor與Proactor模型的對比、Selector的喚醒、Buffer的選擇等。

註:本文的代碼都是偽代碼,主要是為了示意,不可用於生產環境。

傳統BIO模型分析

讓我們先回憶一下傳統的伺服器端同步阻塞I/O處理(也就是BIO,Blocking I/O)的經典編程模型:

{
ExecutorService executor = Excutors.newFixedThreadPollExecutor(100);//線程池

ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(8088);
while(!Thread.currentThread.isInturrupted()){//主線程死循環等待新連接到來
Socket socket = serverSocket.accept();
executor.submit(new ConnectIOnHandler(socket));//為新的連接創建新的線程
}

class ConnectIOnHandler extends Thread{
private Socket socket;
public ConnectIOnHandler(Socket socket){
this.socket = socket;
}
public void run(){
while(!Thread.currentThread.isInturrupted()&&!socket.isClosed()){死循環處理讀寫事件
String someThing = socket.read()....//讀取數據
if(someThing!=null){
......//處理數據
socket.write()....//寫數據
}

}
}
}

這是一個經典的每連接每線程的模型,之所以使用多線程,主要原因在於socket.accept()、socket.read()、socket.write()三個主要函數都是同步阻塞的,當一個連接在處理I/O的時候,系統是阻塞的,如果是單線程的話必然就掛死在那裡;但CPU是被釋放出來的,開啟多線程,就可以讓CPU去處理更多的事情。其實這也是所有使用多線程的本質:

閱讀全文

與javanio網路編程相關的資料

熱點內容
佛教電影《解怨》國語 瀏覽:474
哪部電影男孩叫安東 瀏覽:13
有騎木驢的電影叫什麼感覺 瀏覽:265
windows重啟mysql命令 瀏覽:730
單片機輸入輸出口接收脈沖 瀏覽:121
控制電腦滑鼠的命令 瀏覽:213
男男強暴電影 瀏覽:604
便利店送貨上門app叫什麼 瀏覽:468
win8怎麼打開命令行 瀏覽:129
p開頭的一個看片軟體 瀏覽:755
西班牙電影不準備的愛情 瀏覽:177
python轉換器使用教程 瀏覽:629
cad圖紙重復圖形命令 瀏覽:769
法國女同床戲多私處可見的電影 瀏覽:926
那你給年齡那邊電影想電影想一起電影 瀏覽:994
原耽小說下載 瀏覽:873
香港一級紅色電影 瀏覽:505
三級倫理電影胸大女主角拍的電影有哪些 瀏覽:170
但為君故by龍彌txt 瀏覽:384
mac安裝不了python庫 瀏覽:258