客户端采用的是阻塞io,服务器采用的是nio,客户端向服务器发送了一个字符串,服务端这边读取字节数始终为0,我猜想有可能是未读取完整,使用了while循环反复读取仍然是0,这是为什么呢?有没什么办法解决呢?求大神指导客户端代码public class Tst {
public static void main(String[] args){
try {
Socket socket=new Socket("127.0.0.1",9999);
String[] strs={new String("str1\r\n"),
new String("str2\r\n"),
new String("str3\r\n")};
OutputStream out=socket.getOutputStream();
int i=0;
while(i<3){
try {
Thread.sleep(3000);
System.out.println("准备发送!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(strs[i].getBytes());
out.flush();
i++;
}
if(out!=null){
out.close();
}
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}服务器代码public class TstServer { private Selector selector = null;
static final int port = 9999;
private Charset charset = Charset.forName("UTF-8");
public void init() throws IOException
{
selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(port));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
int readyChannels = selector.select();
if(readyChannels == 0) continue;
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey sk = (SelectionKey) keyIterator.next();
keyIterator.remove();
dealWithSelectionKey(server,sk);
}
}
}
public void dealWithSelectionKey(ServerSocketChannel server,SelectionKey sk) throws IOException {
if(sk.isAcceptable())
{
SocketChannel sc = server.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
sk.interestOps(SelectionKey.OP_ACCEPT);
System.out.println("连接请求来自 :" + sc.getRemoteAddress());
}
//处理来自客户端的数据读取请求
if(sk.isReadable())
{
SocketChannel sc = (SocketChannel)sk.channel();
ByteBuffer buff = ByteBuffer.allocate(1024);
StringBuilder content = new StringBuilder();
try
{
int length=0;
while(true)
{
System.out.println("接收了一次, 大小为" + length);
buff.flip();
content.append(charset.decode(buff));
length=sc.read(buff);
if(length==0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(buff.toString().endsWith("\r\n")) break;
}
System.out.println("Server is listening from client " + sc.getRemoteAddress() + " data rev is: " + content);
sk.interestOps(SelectionKey.OP_READ);
}
catch (IOException io)
{
sk.cancel();
if(sk.channel() != null)
{
sk.channel().close();
}
}
}
}
public static void main(String[] args) throws IOException
{
new TstServer().init();
}
}
public static void main(String[] args){
try {
Socket socket=new Socket("127.0.0.1",9999);
String[] strs={new String("str1\r\n"),
new String("str2\r\n"),
new String("str3\r\n")};
OutputStream out=socket.getOutputStream();
int i=0;
while(i<3){
try {
Thread.sleep(3000);
System.out.println("准备发送!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(strs[i].getBytes());
out.flush();
i++;
}
if(out!=null){
out.close();
}
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}服务器代码public class TstServer { private Selector selector = null;
static final int port = 9999;
private Charset charset = Charset.forName("UTF-8");
public void init() throws IOException
{
selector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress(port));
server.configureBlocking(false);
server.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
int readyChannels = selector.select();
if(readyChannels == 0) continue;
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey sk = (SelectionKey) keyIterator.next();
keyIterator.remove();
dealWithSelectionKey(server,sk);
}
}
}
public void dealWithSelectionKey(ServerSocketChannel server,SelectionKey sk) throws IOException {
if(sk.isAcceptable())
{
SocketChannel sc = server.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
sk.interestOps(SelectionKey.OP_ACCEPT);
System.out.println("连接请求来自 :" + sc.getRemoteAddress());
}
//处理来自客户端的数据读取请求
if(sk.isReadable())
{
SocketChannel sc = (SocketChannel)sk.channel();
ByteBuffer buff = ByteBuffer.allocate(1024);
StringBuilder content = new StringBuilder();
try
{
int length=0;
while(true)
{
System.out.println("接收了一次, 大小为" + length);
buff.flip();
content.append(charset.decode(buff));
length=sc.read(buff);
if(length==0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(buff.toString().endsWith("\r\n")) break;
}
System.out.println("Server is listening from client " + sc.getRemoteAddress() + " data rev is: " + content);
sk.interestOps(SelectionKey.OP_READ);
}
catch (IOException io)
{
sk.cancel();
if(sk.channel() != null)
{
sk.channel().close();
}
}
}
}
public static void main(String[] args) throws IOException
{
new TstServer().init();
}
}
解决方案 »
- 关于何时重写hashCode(),怎样重写hashCode()
- 关于BufferedReader的问题
- 寻找一个函数(急,在线等)
- 散分--刚收到金碟的Offer,想知道金碟里面如何,能不能进去?
- THINK IN JAVA里面的一个例题看不懂 90分答谢解答者
- 又是Applet问题,郁闷(显示图片的)
- 为什么Java的DOS命令使用不了
- 求救~~~我快被JAVA玩死了~~~
- java用什么方法代替C++里的引用功能,菜鸟小问题
- 为什么class文件可以在idea中看到源码
- 连续输出 unicode字符总能有奇怪的事情
- java 父类中this.成员变量 怎么输出父类成员变量,this不是指向当前对象B,不是应该是输出2
第二,使用socket框架吧,nio太原始低级了。自己要搞的细节太多了。使用socket类库一般可靠性高些