导航:首页 > 编程语言 > 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网络编程相关的资料

热点内容
如何对文件夹开启共享 浏览:527
常用的磁盘调度算法 浏览:662
怎么用返利app返利 浏览:127
java代码快速 浏览:241
单片机左移右移后是补1还是0 浏览:597
湛江一号命令 浏览:333
导出命令行 浏览:274
C和php交互 浏览:600
苹果手机里的通讯录如何导入安卓手机 浏览:170
怎么在京东app里面看自己会员等级 浏览:43
emerson服务器怎么短接启动 浏览:559
工控编程人员工资 浏览:397
速成意大利语pdf 浏览:250
连续加减乘除法的算法 浏览:654
用mfc编程实现dda算法 浏览:43
linux命令打开应用 浏览:147
改造后的程序员 浏览:271
数控编程变量 浏览:785
江门哪里有plc编程系统 浏览:379
安卓手机如何下载外服b站 浏览:702