java net io_Exception in thread "main" java.io.IOException: 您的主机中的软件放弃了一个已建立的连接。...

此博客展示了如何使用Java的非阻塞I/O(NIO)实现一个服务器,监听多个端口并接收客户端连接。服务器端通过Selector监控连接,并读取客户端发送的数据进行回显。客户端则向指定服务器发送消息并关闭连接。在实际运行中,服务器可能遇到客户端已关闭连接的情况,导致读取时出错。
摘要由CSDN通过智能技术生成

服务器端代码:

package com.tracy.www;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.ServerSocket;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.util.Iterator;

import java.util.Set;

public class NIOServer {

private int ports[];

private ByteBuffer echoBuffer = ByteBuffer.allocate(1024);

public NIOServer(int ports[]) throws IOException {

this.ports = ports;

go();

}

private void go() throws IOException {

// Create a new selector

Selector selector = Selector.open();

// Open a listener on each port, and register each one

// with the selector

for (int i = 0; i < ports.length; ++i) {

ServerSocketChannel ssc = ServerSocketChannel.open();

ssc.configureBlocking(false);

ServerSocket ss = ssc.socket();

InetSocketAddress address = new InetSocketAddress(ports[i]);

ss.bind(address);

SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);

System.out.println("Going to listen on " + ports[i]);

}

while (true) {

int num = selector.select();

Set selectedKeys = selector.selectedKeys();

Iterator it = selectedKeys.iterator();

while (it.hasNext()) {

SelectionKey key = (SelectionKey) it.next();

if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

// Accept the new connection

ServerSocketChannel ssc = (ServerSocketChannel) key

.channel();

SocketChannel sc = ssc.accept();

sc.configureBlocking(false);

// Add the new connection to the selector

SelectionKey newKey = sc.register(selector,

SelectionKey.OP_READ);

it.remove();

System.out.println("Got connection from " + sc);

} else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

// Read the data

SocketChannel sc = (SocketChannel) key.channel();

// System.out.println(sc.isOpen());

// Echo data

int bytesEchoed = 0;

echoBuffer.clear();

int num1 = sc.read(echoBuffer);

while (num1 > 0) {

echoBuffer.flip();

sc.write(echoBuffer); //此处会报错,由于客户端已经关闭。但是怎么避免这种情况,如果以报错,服务器就会断掉。

bytesEchoed += num1;

num1 = sc.read(echoBuffer);

}

System.out.println(bytesEchoed);

if(num1<0){

System.out.println("关闭");

sc.close();

}

it.remove();

}

}

// System.out.println( "going to clear" );

// selectedKeys.clear();

// System.out.println( "cleared" );

}

}

static public void main(String args[]) throws Exception {

int[] ports = new int[] { 8081, 8080, 45 };

new NIOServer(ports);

}

}

客户端代码:

package com.tracy.client.www;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.OutputStream;

import java.io.OutputStreamWriter;

import java.net.Socket;

import java.net.UnknownHostException;

public class SocketClient {

public static void main(String[] args) {

try {

Socket socket = new Socket("10.152.5.172",8080);

System.out.println( "连接服务器成功。");

OutputStream outputStream=socket.getOutputStream();

OutputStreamWriter oWriter=new OutputStreamWriter(outputStream);

BufferedWriter bWriter=new BufferedWriter(oWriter);

bWriter.write("Hi,NIOServer\r\n\r\n");

bWriter.flush();

try {

Thread.sleep(5000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

bWriter.write("Hi,NIOServer\r\n\r\n");

bWriter.flush();

socket.close();

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值