java网络套接字服务端读取字节数为0

zay12345 2016-08-13 10:09:13
客户端采用的是阻塞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();
}
}
...全文
158 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
attilax 2016-08-14
  • 打赏
  • 举报
回复
第一解决方法,可能是cache的问题,你flush一下,或者多发送几个字符 第二,使用socket框架吧,nio太原始低级了。自己要搞的细节太多了。使用socket类库一般可靠性高些

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧