我用IBM的那个例子,可是无法连接,报错:
java.net.ConnectException: Connection refused: connect
at sun.nio.ch.Net.connect(Native Method)
at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:457)
at nblocksocket.Client.makeConnection(Client.java:25)
at nblocksocket.Client.main(Client.java:92)服务器程序运行在
while (acceptKey.selector().select() > 0) {...}
堵塞住了。还有什么要配置的么?以下是例子程序:Server:
package nblocksocket;import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;
import java.lang.*;public class NonBlockingServer {
public Selector sel = null;
public ServerSocketChannel server = null;
public SocketChannel socket = null;
public int port = 7115;
String result = null; public NonBlockingServer() {
System.out.println("Inside default ctor");
} public NonBlockingServer(int port) {
System.out.println("Inside the other ctor");
this.port = port;
} public void initializeOperations() throws IOException, UnknownHostException {
System.out.println("Inside initialization");
sel = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia, port);
System.out.println(isa.getHostName());
server.socket().bind(isa);
} public void startServer() throws IOException {
System.out.println("Inside startserver");
initializeOperations();
System.out.println("Abt to block on select()");
System.out.println(sel.isOpen());
SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT);
System.out.println(acceptKey.toString());
while (acceptKey.selector().select() > 0) { Set readyKeys = sel.selectedKeys();
Iterator it = readyKeys.iterator(); while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
it.remove(); if (key.isAcceptable()) {
System.out.println("Key is Acceptable");
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
socket = (SocketChannel) ssc.accept();
socket.configureBlocking(false);
SelectionKey another = socket.register(sel,
SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
}
if (key.isReadable()) {
System.out.println("Key is readable");
String ret = readMessage(key);
if (ret.length() > 0) {
writeMessage(socket, ret);
}
}
if (key.isWritable()) {
System.out.println("THe key is writable");
String ret = readMessage(key);
socket = (SocketChannel) key.channel();
if (result.length() > 0) {
writeMessage(socket, ret);
}
}
}
System.out.print("quit1");
}
System.out.print("quit2");
} public void writeMessage(SocketChannel socket, String ret) {
System.out.println("Inside the loop"); if (ret.equals("quit") || ret.equals("shutdown")) {
return;
}
File file = new File(ret);
try { RandomAccessFile rdm = new RandomAccessFile(file, "r");
FileChannel fc = rdm.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
fc.read(buffer);
buffer.flip(); Charset set = Charset.forName("us-ascii");
CharsetDecoder dec = set.newDecoder();
CharBuffer charBuf = dec.decode(buffer);
System.out.println(charBuf.toString());
buffer = ByteBuffer.wrap( (charBuf.toString()).getBytes());
int nBytes = socket.write(buffer);
System.out.println("nBytes = " + nBytes);
result = null;
}
catch (Exception e) {
e.printStackTrace();
} } public String readMessage(SelectionKey key) {
int nBytes = 0;
socket = (SocketChannel) key.channel();
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
nBytes = socket.read(buf);
buf.flip();
Charset charset = Charset.forName("us-ascii");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = charBuffer.toString(); }
catch (IOException e) {
e.printStackTrace();
}
return result;
} public static void main(String args[]) {
NonBlockingServer nb = new NonBlockingServer();
try {
nb.startServer();
}
catch (IOException e) {
e.printStackTrace();
System.exit( -1);
} }
}
Clinet:
package nblocksocket;import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.io.*;
import java.nio.channels.spi.*;
import java.nio.charset.*;
import java.lang.*;public class Client {
public SocketChannel client = null;
public InetSocketAddress isa = null;
public RecvThread rt = null; public Client() {
} public void makeConnection() {
int result = 0;
try { client = SocketChannel.open();
isa = new InetSocketAddress("127.0.0.1", 7115);
client.connect(isa);
client.configureBlocking(false);
receiveMessage();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
while ( (result = sendMessage()) != -1) {
} try {
client.close();
System.exit(0);
}
catch (IOException e) {
e.printStackTrace();
}
} public int sendMessage() {
System.out.println("Inside SendMessage");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
ByteBuffer bytebuf = ByteBuffer.allocate(1024);
int nBytes = 0;
try {
msg = in.readLine();
System.out.println("msg is " + msg);
bytebuf = ByteBuffer.wrap(msg.getBytes());
nBytes = client.write(bytebuf);
System.out.println("nBytes is " + nBytes);
if (msg.equals("quit") || msg.equals("shutdown")) {
System.out.println("time to stop the client");
interruptThread();
try {
Thread.sleep(5000);
}
catch (Exception e) {
e.printStackTrace();
}
client.close();
return -1;
} }
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Wrote " + nBytes + " bytes to the server");
return nBytes;
} public void receiveMessage() {
rt = new RecvThread("Receive THread", client);
rt.start(); } public void interruptThread() {
rt.val = false;
} public static void main(String args[]) {
Client cl = new Client();
cl.makeConnection();
} public class RecvThread
extends Thread {
public SocketChannel sc = null;
public boolean val = true; public RecvThread(String str, SocketChannel client) {
super(str);
sc = client;
} public void run() { System.out.println("Inside receivemsg");
int nBytes = 0;
ByteBuffer buf = ByteBuffer.allocate(2048);
try {
while (val) {
while ( (nBytes = nBytes = client.read(buf)) > 0) {
buf.flip();
Charset charset = Charset.forName("us-ascii");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
String result = charBuffer.toString();
System.out.println(result);
buf.flip(); }
} }
catch (IOException e) {
e.printStackTrace(); } }
}
}
java.net.ConnectException: Connection refused: connect
at sun.nio.ch.Net.connect(Native Method)
at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:457)
at nblocksocket.Client.makeConnection(Client.java:25)
at nblocksocket.Client.main(Client.java:92)服务器程序运行在
while (acceptKey.selector().select() > 0) {...}
堵塞住了。还有什么要配置的么?以下是例子程序:Server:
package nblocksocket;import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.nio.charset.*;
import java.lang.*;public class NonBlockingServer {
public Selector sel = null;
public ServerSocketChannel server = null;
public SocketChannel socket = null;
public int port = 7115;
String result = null; public NonBlockingServer() {
System.out.println("Inside default ctor");
} public NonBlockingServer(int port) {
System.out.println("Inside the other ctor");
this.port = port;
} public void initializeOperations() throws IOException, UnknownHostException {
System.out.println("Inside initialization");
sel = Selector.open();
server = ServerSocketChannel.open();
server.configureBlocking(false);
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia, port);
System.out.println(isa.getHostName());
server.socket().bind(isa);
} public void startServer() throws IOException {
System.out.println("Inside startserver");
initializeOperations();
System.out.println("Abt to block on select()");
System.out.println(sel.isOpen());
SelectionKey acceptKey = server.register(sel, SelectionKey.OP_ACCEPT);
System.out.println(acceptKey.toString());
while (acceptKey.selector().select() > 0) { Set readyKeys = sel.selectedKeys();
Iterator it = readyKeys.iterator(); while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
it.remove(); if (key.isAcceptable()) {
System.out.println("Key is Acceptable");
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
socket = (SocketChannel) ssc.accept();
socket.configureBlocking(false);
SelectionKey another = socket.register(sel,
SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
}
if (key.isReadable()) {
System.out.println("Key is readable");
String ret = readMessage(key);
if (ret.length() > 0) {
writeMessage(socket, ret);
}
}
if (key.isWritable()) {
System.out.println("THe key is writable");
String ret = readMessage(key);
socket = (SocketChannel) key.channel();
if (result.length() > 0) {
writeMessage(socket, ret);
}
}
}
System.out.print("quit1");
}
System.out.print("quit2");
} public void writeMessage(SocketChannel socket, String ret) {
System.out.println("Inside the loop"); if (ret.equals("quit") || ret.equals("shutdown")) {
return;
}
File file = new File(ret);
try { RandomAccessFile rdm = new RandomAccessFile(file, "r");
FileChannel fc = rdm.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
fc.read(buffer);
buffer.flip(); Charset set = Charset.forName("us-ascii");
CharsetDecoder dec = set.newDecoder();
CharBuffer charBuf = dec.decode(buffer);
System.out.println(charBuf.toString());
buffer = ByteBuffer.wrap( (charBuf.toString()).getBytes());
int nBytes = socket.write(buffer);
System.out.println("nBytes = " + nBytes);
result = null;
}
catch (Exception e) {
e.printStackTrace();
} } public String readMessage(SelectionKey key) {
int nBytes = 0;
socket = (SocketChannel) key.channel();
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
nBytes = socket.read(buf);
buf.flip();
Charset charset = Charset.forName("us-ascii");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = charBuffer.toString(); }
catch (IOException e) {
e.printStackTrace();
}
return result;
} public static void main(String args[]) {
NonBlockingServer nb = new NonBlockingServer();
try {
nb.startServer();
}
catch (IOException e) {
e.printStackTrace();
System.exit( -1);
} }
}
Clinet:
package nblocksocket;import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.io.*;
import java.nio.channels.spi.*;
import java.nio.charset.*;
import java.lang.*;public class Client {
public SocketChannel client = null;
public InetSocketAddress isa = null;
public RecvThread rt = null; public Client() {
} public void makeConnection() {
int result = 0;
try { client = SocketChannel.open();
isa = new InetSocketAddress("127.0.0.1", 7115);
client.connect(isa);
client.configureBlocking(false);
receiveMessage();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
while ( (result = sendMessage()) != -1) {
} try {
client.close();
System.exit(0);
}
catch (IOException e) {
e.printStackTrace();
}
} public int sendMessage() {
System.out.println("Inside SendMessage");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String msg = null;
ByteBuffer bytebuf = ByteBuffer.allocate(1024);
int nBytes = 0;
try {
msg = in.readLine();
System.out.println("msg is " + msg);
bytebuf = ByteBuffer.wrap(msg.getBytes());
nBytes = client.write(bytebuf);
System.out.println("nBytes is " + nBytes);
if (msg.equals("quit") || msg.equals("shutdown")) {
System.out.println("time to stop the client");
interruptThread();
try {
Thread.sleep(5000);
}
catch (Exception e) {
e.printStackTrace();
}
client.close();
return -1;
} }
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Wrote " + nBytes + " bytes to the server");
return nBytes;
} public void receiveMessage() {
rt = new RecvThread("Receive THread", client);
rt.start(); } public void interruptThread() {
rt.val = false;
} public static void main(String args[]) {
Client cl = new Client();
cl.makeConnection();
} public class RecvThread
extends Thread {
public SocketChannel sc = null;
public boolean val = true; public RecvThread(String str, SocketChannel client) {
super(str);
sc = client;
} public void run() { System.out.println("Inside receivemsg");
int nBytes = 0;
ByteBuffer buf = ByteBuffer.allocate(2048);
try {
while (val) {
while ( (nBytes = nBytes = client.read(buf)) > 0) {
buf.flip();
Charset charset = Charset.forName("us-ascii");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
String result = charBuffer.toString();
System.out.println(result);
buf.flip(); }
} }
catch (IOException e) {
e.printStackTrace(); } }
}
}
InetAddress ia = InetAddress.getLocalHost();
isa = new InetSocketAddress(ia,7115);
替换
isa = new InetSocketAddress("127.0.0.1", 7115);
就可以。为什么?
isa = new InetSocketAddress(ia.getHostAddress(),7115);
1.连接数大于数据库中设定的最大连接数的时候.
2.服务器的主机名和端口设置不正确
默认 启用了 host 解析的, 里面至少有一条 127.0.0.1 localhost .
如果你禁用了 host 解析或者用 3721 清理了 那个文件就用 DNS 解析失败.