Rumah > Soal Jawab > teks badan
直接上代码。
client端:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class JavaTest {
public static void main(String[] args) throws Exception {
SocketChannel client = SocketChannel.open();
client.connect(new InetSocketAddress("127.0.0.1", 30003));
ByteBuffer buffer = ByteBuffer.allocate(1024);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String console = null;
byte[] bytes = new byte[1024];
while ((console = bufferedReader.readLine()) != null) {
buffer.clear();
buffer.put(console.getBytes(), 0, console.getBytes().length);
int n = client.write(buffer);
System.out.println("Client write: " + n);
buffer.flip();
n = client.read(buffer);
System.out.println("Client read: " + n);
buffer.get(bytes, 0, n);
buffer.flip();
System.out.println(new String(bytes));
}
client.close();
}
}
server端代码:
import java.net.InetSocketAddress;
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 Test {
public static void main(String args[]) throws Exception
{
ServerSocketChannel server = ServerSocketChannel.open();
server.socket().bind(new InetSocketAddress("127.0.0.1", 30003));
Selector selector = Selector.open();
server.configureBlocking(false);
SelectionKey skey = server.register(selector, SelectionKey.OP_ACCEPT);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
selector.select();
Set<SelectionKey> result = selector.selectedKeys();
Iterator<SelectionKey> resultIterator = result.iterator();
while (resultIterator.hasNext()) {
SelectionKey eachone = (SelectionKey)resultIterator.next();
//if server has an acceptable client
if (eachone.isAcceptable()) {
ServerSocketChannel acceptChannel = (ServerSocketChannel)eachone.channel();
//new client
SocketChannel client = acceptChannel.accept();
client.configureBlocking(false);
SelectionKey clientkey = acceptChannel.register(selector, SelectionKey.OP_READ);
} else if (eachone.isReadable()) {
SocketChannel client = (SocketChannel)eachone.channel();
//readable client
byte[] bytes = new byte[1024];
buffer.clear();
int n = client.read(buffer);
System.out.println("Server read: " + n);
buffer.flip();
buffer.get(bytes, 0, n);
System.out.println(new String(bytes));
buffer.flip();
n = client.write(buffer);
System.out.println("Server write: " + n);
client.close();
}
resultIterator.remove();
}
}
}
}
client端从System.in读入一行字符,write到server端,再从server端read,将server端发回来的字符串输出到System.out上。
调式时出错了,求问为什么。