做的功能是这样的。发送者、服务器、接受者、。要求一端发送到服务器。。服务器接收然后发送到接收者输出结束代码发送者和接收者写一起就正常。但是发送者接收者一分开就失败。。晕倒啊。。 老大们帮忙看看接收端怎么写吧。。迟迟接不到东西啊
代码如下:
服务器:package src.mygame.StringTest;import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;public class NioServer { static int BLOCK = 1024;
static String name = "";
protected Selector selector;
protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
protected CharsetDecoder decoder;
static CharsetEncoder encoder = Charset.forName("gbk").newEncoder(); public NioServer(int port) throws IOException {
selector = this.getSelector(port);
Charset charset = Charset.forName("gbk");
decoder = charset.newDecoder();
} // 获取Selector
protected Selector getSelector(int port) throws IOException {
ServerSocketChannel server = ServerSocketChannel.open();
Selector sel = Selector.open();
server.socket().bind(new InetSocketAddress("localhost",port));
server.configureBlocking(false);
server.register(sel, SelectionKey.OP_ACCEPT);
return sel;
}
// 监听端口
public void listen() {
try {
for (;;) {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
process(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} // 处理事件
protected void process(SelectionKey key) throws IOException {
if (key.isAcceptable()) { // 接收请求
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
//设置非阻塞模式
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) { // 读信息
SocketChannel channel = (SocketChannel) key.channel();
int count = channel.read(clientBuffer);
if (count > 0) {
clientBuffer.flip();
CharBuffer charBuffer = decoder.decode(clientBuffer);
name = charBuffer.toString();
System.out.println(name);
SelectionKey sKey = channel.register(selector,
SelectionKey.OP_WRITE);
sKey.attach(name);
} else {
channel.close();
} clientBuffer.clear();
} else if (key.isWritable()) { // 写事件
SocketChannel channel = (SocketChannel) key.channel();
String name = (String) key.attachment();
ByteBuffer block = encoder.encode(CharBuffer
.wrap("Hello !" + name));
channel.write(block); channel.close(); }
} public static void main(String[] args) {
int port = 2008;
try {
NioServer server = new NioServer(port);
System.out.println("listening on " + port);
server.listen();
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码如下:
服务器:package src.mygame.StringTest;import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;public class NioServer { static int BLOCK = 1024;
static String name = "";
protected Selector selector;
protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
protected CharsetDecoder decoder;
static CharsetEncoder encoder = Charset.forName("gbk").newEncoder(); public NioServer(int port) throws IOException {
selector = this.getSelector(port);
Charset charset = Charset.forName("gbk");
decoder = charset.newDecoder();
} // 获取Selector
protected Selector getSelector(int port) throws IOException {
ServerSocketChannel server = ServerSocketChannel.open();
Selector sel = Selector.open();
server.socket().bind(new InetSocketAddress("localhost",port));
server.configureBlocking(false);
server.register(sel, SelectionKey.OP_ACCEPT);
return sel;
}
// 监听端口
public void listen() {
try {
for (;;) {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
process(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} // 处理事件
protected void process(SelectionKey key) throws IOException {
if (key.isAcceptable()) { // 接收请求
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
//设置非阻塞模式
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) { // 读信息
SocketChannel channel = (SocketChannel) key.channel();
int count = channel.read(clientBuffer);
if (count > 0) {
clientBuffer.flip();
CharBuffer charBuffer = decoder.decode(clientBuffer);
name = charBuffer.toString();
System.out.println(name);
SelectionKey sKey = channel.register(selector,
SelectionKey.OP_WRITE);
sKey.attach(name);
} else {
channel.close();
} clientBuffer.clear();
} else if (key.isWritable()) { // 写事件
SocketChannel channel = (SocketChannel) key.channel();
String name = (String) key.attachment();
ByteBuffer block = encoder.encode(CharBuffer
.wrap("Hello !" + name));
channel.write(block); channel.close(); }
} public static void main(String[] args) {
int port = 2008;
try {
NioServer server = new NioServer(port);
System.out.println("listening on " + port);
server.listen();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;public class ProducerClient { static int SIZE = 10;
static InetSocketAddress ip = new InetSocketAddress("localhost", 2008);
static CharsetEncoder encoder = Charset.forName("gbk").newEncoder(); static class Message implements Runnable {
protected String name;
String msg = ""; public Message(String index) {
this.name = index;
} public void run() {
try {
long start = System.currentTimeMillis();
//打开Socket通道
SocketChannel client = SocketChannel.open();
//设置为非阻塞模式
client.configureBlocking(false);
//打开选择器
Selector selector = Selector.open();
//注册连接服务端socket动作
client.register(selector, SelectionKey.OP_CONNECT);
//连接
client.connect(ip);
//分配内存
ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
FOR: for (;;) {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key
.channel();
if (channel.isConnectionPending())
channel.finishConnect();
channel
.write(encoder
.encode(CharBuffer.wrap(name)));
break FOR;
}
}
}
System.out.println(msg );
msg = "";
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws IOException { String names[] = new String[SIZE]; for (int index = 0; index < SIZE; index++) {
names[index] = "msg[" + index + "]";
new Thread(new Message(names[index])).start();
} }
}接收端:问题所在啊。。
[code=Java]
package src.mygame.StringTest;import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;public class ConsumerClient { static int SIZE = 10;
static InetSocketAddress ip = new InetSocketAddress("localhost", 2008);
static CharsetEncoder encoder = Charset.forName("gbk").newEncoder();
static double totaltime=0;
static class Message implements Runnable {
protected String name;
String msg = ""; public Message(String index) {
this.name = index;
} public void run() {
try {
long start = System.currentTimeMillis();
//打开Socket通道
SocketChannel client = SocketChannel.open();
//设置为非阻塞模式
client.configureBlocking(false);
//打开选择器
Selector selector = Selector.open();
//注册连接服务端socket动作
client.register(selector, SelectionKey.OP_READ);
//连接
client.connect(ip);
//分配内存
ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
int total = 0; FOR: for (;;) {
selector.select();
Iterator iter = selector.selectedKeys().iterator(); while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key
.channel();
if (channel.isConnectionPending())
channel.finishConnect();
// channel
// .write(encoder
// .encode(CharBuffer.wrap(name))); channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key
.channel();
int count = channel.read(buffer);
if (count > 0) {
total += count;
buffer.flip(); while (buffer.remaining() > 0) {
byte b = buffer.get();
msg += (char) b;
}
System.out.println("meg is :"+msg);
buffer.clear();
} else {
client.close();
break FOR;
}
}
}
}
double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
System.out.println(msg + "used time :" + last + "s");
totaltime=totaltime+last;
msg = "";
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws IOException {
new Thread(new Message("111")).start();
}
}[/code]