Java Nio中Charset的decode()方法问题
    try {
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);
        System.out.println("capacity = " + byteBuffer.capacity() + ", limit = " + byteBuffer.limit() + ", position = " + byteBuffer.position());

        FileChannel channel = new FileInputStream(PATH).getChannel();
        channel.read(byteBuffer);

        System.out.println("capacity = " + byteBuffer.capacity() + ", limit = " + byteBuffer.limit() + ", position = " + byteBuffer.position());
    byteBuffer.clear();
        System.out.println("capacity = " + byteBuffer.capacity() + ", limit = " + byteBuffer.limit() + ", position = " + byteBuffer.position());

        CharBuffer buffer = Charset.defaultCharset().decode(byteBuffer);
        System.out.println("capacity = " + buffer.capacity() + ", limit = " + buffer.limit() + ", position = " + buffer.position());
    } catch (Exception e) {
        e.printStackTrace();
    }

代码如上,假设有一个文件是系统默认GBK编码,文件内容只有一个数字1,那么上述代码在decode之后得到的CharBuffer的容量为什么是21,比原ByteBuffer都大?而且CharBuffer的容量与极限为什么不同?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java nio通信问题如何解决
大佬们帮我看看这句代码,我有点理解不了:![图片说明](https://img-ask.csdn.net/upload/201706/02/1496365514_646261.png) 这句代码的前面是获取欲与服务器端建立联系的selectionkey的作用,但是server.accept()这句代码并没有和相应的selectionkey对应,jdk只是说这句代码的作用只是获取此刻与服务器channel建立连接的socketchannel而不是此刻正在被检查的selectionkey的对应的socketchannel,那前面的那句sk.isAccpetable()不就起不到作用了吗?请知道的大侠告诉下。代码如下: public class NServer { //用于检测所有Channel状态的Selector private Selector selector=null; static final int PORT=3334; //定义实现编码、解码的字符集对象 private Charset charset=Charset.forName("UTF-8"); public void init() { try { selector=Selector.open(); //通过open方法来打开一个未绑定的ServerSocketChannel实例 ServerSocketChannel server=ServerSocketChannel.open(); InetSocketAddress isa=new InetSocketAddress("127.0.0.1",PORT); //将该ServerSocketChannel绑定到指定IP地址 server.bind(isa); //设置ServerSocket以非阻塞方式工作 server.configureBlocking(false); //将server注册到指定的Selector对象 server.register(selector,SelectionKey.OP_ACCEPT); while(true) //说明有需要处理的IO对象 { if(selector.select()==0)continue; //依次处理selector上的每个选择的SelectionKey for(SelectionKey sk :selector.selectedKeys()) { //从selector上的已选择Key集中删除正在处理的SelectionKey selector.selectedKeys().remove(sk); //如果sk对应的Channel包含客户端的连接请求 if(sk.isAcceptable()) { //调用accept方法接受连接,产生服务端的SocketChannel SocketChannel sc=server.accept(); //设置采用非阻塞模式 if (sc == null) { continue; } sc.configureBlocking(false); //将该SocketChannel也注册到selector //后面的read表示我们可以向通道那里读入数据了 // System.out.println("@@@@@@@@@@@@"); sc.register(selector, SelectionKey.OP_READ); //将sk对应的Channel设置成准备接收其他请求 //sk.interestOps(SelectionKey.OP_ACCEPT); } //如果sk对应的Channel有数据需要读取 if(sk.isReadable()) { //System.out.println("@@@@@@@@@@@@"); //获取该SelectionKey对应的Channel,该Channel中有可读的数据 SocketChannel sc=(SocketChannel) sk.channel(); //定义准备执行读取数据的ByteBuffer ByteBuffer buff=ByteBuffer.allocate(1024); String content=""; //开始读取数据 try { while(sc.read(buff)>0) { buff.flip(); content+=charset.decode(buff); } //打印从该sk对应的Channel里读取到的数据 while(sc.write(buff)>0) { buff.clear(); content+=charset.decode(buff); } //将sk对应的Channel设置成准备下一次读取 sk.interestOps(SelectionKey.OP_READ); System.out.println("Server收到信息了: "+content); if(content.length()<5) { sc.write(charset.encode("你发过来的长度小于5")); } else if(content.length()<9) { sc.write(charset.encode("你发过来的长度小于9")); } }catch(IOException ex) { //从Selector中删除指定的SelectionKey sk.cancel(); if(sk.channel()!=null) { sk.channel().close(); } } //sc.write(charset.encode(line)); } } } } catch (IOException e) { // TODO 自动生成的 catch 块 //System.out.println("出错了"); e.printStackTrace(); } } class Thread3 extends Thread { public void run() { init(); System.out.println("结束了"); } } public static void main(String[]args) { new NServer().new Thread3().start(); } }
java nio的select和linux的epoll有什么区别?
#### 最近在看关于epoll和select相关问题,但是并没有发现java的select和linux的epoll有什么区别 #### java的nio select代码如下 ``` import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; 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.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; public class NioServer { private static Map<String, SocketChannel> clientMap = new HashMap<>(); public static void main(String[] args) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); ServerSocket serverSocket = serverSocketChannel.socket(); serverSocket.bind(new InetSocketAddress(8899)); Selector selector = Selector.open(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { try { /** * 程序会卡在select()函数,当客户端有动作了,比如连接上了,或者是发送消息过来了,服务端才会继续走 * 当第一个客户端连接上并且是selectionKey.isAcceptable(),代码就又重新卡到了select()函数上 * 等待客户端的再次操作(无论是哪个客户端) */ selector.select(); /** * selector.selectedKeys()这段代码可以从中知道是哪个客户端,执行了什么操作 * */ Set<SelectionKey> selectionKeys = selector.selectedKeys(); selectionKeys.forEach((selectionKey) -> { final SocketChannel client; try { if (selectionKey.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel(); /** * 这代代码获取了真正的客户端socket句柄 */ client = server.accept(); client.configureBlocking(false); /** * 这句话如果不写,就相当于没有注册当消息可读时的回调函数,当客户端发送消息过来的时候 * 服务端的selector.selectedKeys()就永远不会受到这类消息 */ client.register(selector, SelectionKey.OP_READ); String key = "[" + UUID.randomUUID().toString() + "]"; clientMap.put(key, client); } else if (selectionKey.isReadable()) { client = (SocketChannel) selectionKey.channel(); ByteBuffer readBuffer = ByteBuffer.allocate(1024); int count = client.read(readBuffer); if (count > 0) { readBuffer.flip(); Charset charset = Charset.forName("utf-8"); String recvMsg = String.valueOf(charset.decode(readBuffer).array()); System.out.println(client + ":" + recvMsg); String sendKey = null; for (Map.Entry<String, SocketChannel> stringSocketChannelEntry : clientMap.entrySet()) { if (stringSocketChannelEntry.getValue() == client) { sendKey = stringSocketChannelEntry.getKey(); break; } } for (Map.Entry<String, SocketChannel> stringSocketChannelEntry : clientMap.entrySet()) { SocketChannel socketChannel = stringSocketChannelEntry.getValue(); ByteBuffer writeBuffer = ByteBuffer.allocate(1024); writeBuffer.put((sendKey + ": " + recvMsg).getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); } } } } catch (Exception ex) { ex.printStackTrace(); } }); selectionKeys.clear(); } catch (Exception e) { e.printStackTrace(); } } } } ``` #### linux的epoll的c代码如下 ``` #include <iostream> #include <sys/socket.h> #include <sys/epoll.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include <cstring> using namespace std; #define MAXLINE 5 #define OPEN_MAX 100 #define LISTENQ 20 #define SERV_PORT 5000 #define INFTIM 1000 void setnonblocking(int sock) { int opts; opts=fcntl(sock,F_GETFL); if(opts<0) { perror("fcntl(sock,GETFL)"); exit(1); } opts = opts|O_NONBLOCK; if(fcntl(sock,F_SETFL,opts)<0) { perror("fcntl(sock,SETFL,opts)"); exit(1); } } int main(int argc, char* argv[]) { int i, maxi, listenfd, connfd, sockfd,epfd,nfds, portnumber; ssize_t n; char line[MAXLINE]; socklen_t clilen; if ( 2 == argc ) { if( (portnumber = atoi(argv[1])) < 0 ) { fprintf(stderr,"Usage:%s portnumber/a/n",argv[0]); return 1; } } else { fprintf(stderr,"Usage:%s portnumber/a/n",argv[0]); return 1; } //声明epoll_event结构体的变量,ev用于注册事件,数组用于回传要处理的事件 struct epoll_event ev,events[20]; //生成用于处理accept的epoll专用的文件描述符 //创建一个epoll文件描述符 epfd=epoll_create(256); struct sockaddr_in clientaddr; struct sockaddr_in serveraddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); //把socket设置为非阻塞方式 //setnonblocking(listenfd); //设置与要处理的事件相关的文件描述符 ev.data.fd=listenfd; //设置要处理的事件类型 ev.events=EPOLLIN|EPOLLET; //ev.events=EPOLLIN; //注册epoll事件,将socket文件描述符listenfd的ev事件注册到epoll上 epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev); memset(&serveraddr, sizeof(serveraddr) ,0); serveraddr.sin_family = AF_INET; char *local_addr="127.0.0.1"; inet_aton(local_addr,&(serveraddr.sin_addr));//htons(portnumber); serveraddr.sin_port=htons(portnumber); //先bind再监听 bind(listenfd,(sockaddr *)&serveraddr, sizeof(serveraddr)); listen(listenfd, LISTENQ); maxi = 0; for ( ; ; ) { //等待epoll事件的发生 //param epfd表示将监听epfd的事件 //param events表示容器,一旦有事件发生,events数组会被填充 nfds=epoll_wait(epfd,events,20,500); //处理所发生的所有事件 for(i=0;i<nfds;++i) { if(events[i].data.fd==listenfd)//如果新监测到一个SOCKET用户连接到了绑定的SOCKET端口,建立新的连接。 { connfd = accept(listenfd,(sockaddr *)&clientaddr, &clilen); if(connfd<0){ perror("connfd<0"); exit(1); } //setnonblocking(connfd); char *str = inet_ntoa(clientaddr.sin_addr); cout << "accapt a connection from " << str << endl; //设置用于读操作的文件描述符 ev.data.fd=connfd; //设置用于注测的读操作事件 ev.events=EPOLLIN|EPOLLET; //ev.events=EPOLLIN; //注册ev epoll_ctl(epfd,EPOLL_CTL_ADD,connfd,&ev); } else if(events[i].events&EPOLLIN)//如果是已经连接的用户,并且收到数据,那么进行读入。 { cout << "EPOLLIN" << endl; if ( (sockfd = events[i].data.fd) < 0) continue; if ( (n = read(sockfd, line, MAXLINE)) < 0) { if (errno == ECONNRESET) { close(sockfd); events[i].data.fd = -1; } else std::cout<<"readline error"<<std::endl; } else if (n == 0) { close(sockfd); events[i].data.fd = -1; } line[n] = '/0'; cout << "read " << line << endl; //设置用于写操作的文件描述符 ev.data.fd=sockfd; //设置用于注测的写操作事件 ev.events=EPOLLOUT|EPOLLET; //修改sockfd上要处理的事件为EPOLLOUT //epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev); } else if(events[i].events&EPOLLOUT) // 如果有数据发送 { sockfd = events[i].data.fd; write(sockfd, line, n); //设置用于读操作的文件描述符 ev.data.fd=sockfd; //设置用于注测的读操作事件 ev.events=EPOLLIN|EPOLLET; //修改sockfd上要处理的事件为EPOLIN epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev); } } } return 0; } ``` #### 从上面两段代码看好像基本思想都是一样的,并没有传说中的select不知道发生的事件,只能通过循环去判断的情况。 #### 但是后来我又在网上找了一段linux的select实现的网络io代码 ``` #include<stdio.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<stdlib.h> #include<errno.h> #include<arpa/inet.h> #include<netinet/in.h> #include<string.h> #include<signal.h> #define MAXLINE 1024 #define LISTENLEN 10 #define SERV_PORT 6666 int main(int argc, char **argv) { int i, maxi, maxfd, listenfd, connfd, sockfd; int nready, client[FD_SETSIZE]; ssize_t n; fd_set rset, allset; char buf[MAXLINE]; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); bind(listenfd, (struct sockaddr*) &servaddr, sizeof(servaddr)); listen(listenfd, LISTENLEN); maxfd = listenfd; /* initialize */ maxi = -1; /* index into client[] array */ for (i = 0; i < FD_SETSIZE; i++) client[i] = -1; /* -1 indicates available entry */ FD_ZERO(&allset); FD_SET(listenfd, &allset); for ( ; ; ) { rset = allset; /* structure assignment */ nready = select(maxfd+1, &rset, NULL, NULL, NULL); if (FD_ISSET(listenfd, &rset)) /* new client connection */ { clilen = sizeof(cliaddr); connfd = accept(listenfd, (struct sockaddr*) &cliaddr, &clilen); #ifdef NOTDEF printf("new client: %s, port %d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, 4, NULL), ntohs(cliaddr.sin_port)); #endif for (i = 0; i < FD_SETSIZE; i++) if (client[i] < 0) { client[i] = connfd; /* save descriptor */ break; } if (i == FD_SETSIZE) { printf("too many clients"); exit(0); } FD_SET(connfd, &allset); /* add new descriptor to set */ if (connfd > maxfd) maxfd = connfd; /* for select */ if (i > maxi) maxi = i; /* max index in client[] array */ if (--nready <= 0) continue; /* no more readable descriptors */ } for (i = 0; i <= maxi; i++) /* check all clients for data */ { if ( (sockfd = client[i]) < 0) continue; if (FD_ISSET(sockfd, &rset)) { if ( (n = read(sockfd, buf, MAXLINE)) == 0)/* connection closed by client */ { close(sockfd); FD_CLR(sockfd, &allset); client[i] = -1; } else write(sockfd, buf, n); if (--nready <= 0) break; /* no more readable descriptors */ } } } } ``` #### 从这段代码里面确实是可以看出是通过循环判断的,我的问题是java的select是不是就是linux的epoll的思想?
java nio SelectionKey isWritable为什么一直是true
服务器 [code="java"] package test.nio; 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.util.Iterator; import java.util.Set; public class NonBlockEchoServer { private ServerSocketChannel serverSocketChannel; private int port = 8992; private Selector selector; private Charset charset; public NonBlockEchoServer() throws IOException { charset = Charset.forName("UTF-8"); selector = Selector.open(); serverSocketChannel = ServerSocketChannel.open(); //可以绑定到同一个端口 serverSocketChannel.socket().setReuseAddress(true); //设置为非阻塞模式 serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(port)); } public void service() throws IOException { serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while(selector.select() > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> it = keys.iterator(); while(it.hasNext()) { SelectionKey key = null; try { key = it.next(); it.remove(); if(key.isAcceptable()) { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); ByteBuffer byteBuffer = ByteBuffer.allocate(0); socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE, byteBuffer); } if(key.isReadable()) { read(key); } if(key.isWritable()) { write(key); } }catch (IOException e) { if(key != null) { try { key.cancel(); key.channel().close(); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } } } } private void write(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); ByteBuffer byteBuffer = (ByteBuffer) key.attachment(); byteBuffer.flip(); String data = decode(byteBuffer); if(data.indexOf("\r\n") == -1) { return; } String outputData = data.substring(0, data.indexOf("\n")+1); System.out.println("--->" + outputData); ByteBuffer outputBuffer = encode("echo:" + outputData); while(outputBuffer.hasRemaining()) { socketChannel.write(outputBuffer); } ByteBuffer temp = encode(outputData); byteBuffer.position(temp.limit()); byteBuffer.compact(); if(outputData.equals("bye\r\n")) { key.cancel(); socketChannel.close(); System.out.println("链接已经关闭"); } } private void read(SelectionKey key) throws IOException { System.out.println("server read"); SocketChannel socketChannel = (SocketChannel) key.channel(); socketChannel.configureBlocking(false); ByteBuffer byteBuffer = (ByteBuffer) key.attachment(); ByteBuffer readBuff = ByteBuffer.allocate(32); socketChannel.read(readBuff); byteBuffer.limit(byteBuffer.capacity()); readBuff.flip(); byteBuffer.put(readBuff); } /** * 解码 * @param byteBuffer * @return */ private String decode(ByteBuffer byteBuffer) { CharBuffer charBuffer = charset.decode(byteBuffer); return charBuffer.toString(); } /** * 编码 * @param str * @return */ private ByteBuffer encode(String str) { return charset.encode(str); } public static void main(String[] args) throws IOException { NonBlockEchoServer nonServer = new NonBlockEchoServer(); nonServer.service(); } } [/code] 客户端 [code="java"] package test.nio; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Iterator; import java.util.Set; public class NonBlockEchoClient { private SocketChannel socketChannel; private ByteBuffer sendBuffer = ByteBuffer.allocate(1024); private ByteBuffer receiveBuffer = ByteBuffer.allocate(1024); Charset charset = Charset.forName("utf-8"); private Selector selector; private int port = 8992; public NonBlockEchoClient() throws IOException { socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress(port)); socketChannel.configureBlocking(false); System.out.println("与服务器链接成功"); selector = Selector.open(); } public static void main(String[] args) throws IOException { final NonBlockEchoClient non = new NonBlockEchoClient(); Thread client = new Thread(new Runnable() { @Override public void run() { non.receiveFromUser(); } }); client.start(); non.talk(); } private void talk() throws IOException { socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE); while(selector.select() > 0) { Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> it = keys.iterator(); while(it.hasNext()) { SelectionKey key = it.next(); it.remove(); if(key.isReadable()) { receive(key); } if(key.isWritable()) { send(key); } } } } public void receiveFromUser() { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String msg = null; while((msg = bufferedReader.readLine()) != null) { System.out.println(msg); synchronized (sendBuffer) { sendBuffer.put(encode(msg+"\r\n")); } if("bye".equals(msg)) { break; } } } catch(IOException e) { e.printStackTrace(); } } private void send(SelectionKey key) throws IOException { SocketChannel socketChannel = (SocketChannel) key.channel(); synchronized (sendBuffer) { sendBuffer.flip(); socketChannel.write(sendBuffer); sendBuffer.compact(); } } private void receive(SelectionKey key) throws IOException { System.out.println("client RECEIVE"); SocketChannel socketChannel = (SocketChannel) key.channel(); socketChannel.read(receiveBuffer); receiveBuffer.flip(); String receiveData = decode(receiveBuffer); if(receiveData.indexOf("\n") == -1) return; String outputData = receiveData.substring(0, receiveData.indexOf("\n") + 1); System.out.println("--->" + outputData); if(outputData.equals("echo:bye\r\n")) { key.cancel(); socketChannel.close(); selector.close(); System.exit(0); } ByteBuffer temp = encode(outputData); receiveBuffer.position(temp.limit()); receiveBuffer.compact(); } private String decode(ByteBuffer byteBuffer) { return charset.decode(byteBuffer).toString(); } private ByteBuffer encode(String str) { return charset.encode(str); } } [/code] 各位大侠,最近小弟在学习nio编程,遇到一个问题:客户端在连接服务器端成功后,没有进行任何操作,服务器端并没有触发 写事件 为什么key.isWritable()一直为true ??
NIO 不调用iterator的remove的问题
package chatIO; import java.io.IOException; 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.nio.charset.Charset; import java.util.Iterator; public class chatServiceNIO { private static final int BUFSIZE = 256; // Buffer size (bytes) private static final int TIMEOUT = 3000; // Wait timeout (milliseconds) public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel listnChannel = ServerSocketChannel.open(); listnChannel.socket().bind(new InetSocketAddress(9090)); listnChannel.configureBlocking(false); // must be nonblocking to // register listnChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select(TIMEOUT) == 0) { // returns # of ready chans System.out.print("."); continue; } Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); while (keyIter.hasNext()) { SelectionKey key = keyIter.next(); // Key is bit mask if (key.isAcceptable()) { System.out.println("accept...."); SocketChannel sc = ((ServerSocketChannel) key.channel()).accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } if (key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer bb = ByteBuffer.allocate(300); sc.read(bb); bb.flip(); System.out.println(Charset.forName("UTF-8").decode(bb)); } //keyIter.remove(); // remove from set of selected keys } } } } ``` ``` 这里我把iterator的remove注释了 为什么select()方法就一直返回0了啊 即使有新的连接进入 不太懂这个原理 麻烦又大神能讲下吗 万分感谢
java ByteBuffer clear()问题,下面这段代码为什么会死循环
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { File f=new File("D:/1.txt"); FileChannel chanel=new RandomAccessFile(f,"rw").getChannel(); MappedByteBuffer map=chanel.map(FileChannel.MapMode.READ_ONLY,0,f.length() ); java.nio.ByteBuffer buffer=java.nio.ByteBuffer.allocate(256); Charset charset=Charset.forName("utf-8"); CharsetDecoder decorder=charset.newDecoder(); while((chanel.read(buffer))!=-1){ buffer.flip(); CharBuffer cb=charset.decode(buffer); System.out.println(cb); //buffer.clear(); } }
java这个简单的服务器我要如何读取客户端的输入信息?
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; 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.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Set; public class EchoServer { public static int DEFAULT_PORT = 7; public static String text=""; public static ServerSocketChannel server; public static SocketChannel client ; public static ByteBuffer output ; public static void main(String[] args){ int port; try{ port = Integer.parseInt(args[0]); }catch(RuntimeException ex){ port = DEFAULT_PORT; } System.out.println("Listening for connertions on port "+port); ServerSocketChannel serverChannel; Selector selector; try{ serverChannel = ServerSocketChannel.open(); ServerSocket ss = serverChannel.socket(); InetSocketAddress address = new InetSocketAddress(port); ss.bind(address); serverChannel.configureBlocking(false); selector =Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); }catch(IOException ex){ ex.printStackTrace(); return; } while(true){ try{ selector.select(); }catch(IOException ex){ ex.printStackTrace(); break; } Set<SelectionKey> readyKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = readyKeys.iterator(); while(iterator.hasNext()){ SelectionKey key = iterator.next(); iterator.remove(); try{ if(key.isAcceptable()){ ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel client = server.accept(); System.out.println("Accepted connection from "+client); client.configureBlocking(false); SelectionKey clientKey = client.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ); ByteBuffer buffer = ByteBuffer.allocate(100); clientKey.attach(buffer); } if(key.isReadable()){ client =(SocketChannel)key.channel(); output = (ByteBuffer)key.attachment(); client.read(output); output.flip(); Charset charset = Charset.forName("UTF-8"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = null; charBuffer = decoder.decode(output); text=charBuffer.toString(); //if(text.equals("time")) //{ //System.out.println("2"); Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time=format.format(date); byte b[] = time.getBytes(); //将十六进制字符串转换成十进制整数 //int i=Integer.decode(time); //创建一个大小为1的字节缓冲区因为只放一个byte值 ByteBuffer bb=ByteBuffer.allocate(1); //将十进制整数转换成二进制byte值然后存进ByteBuffer //bb.put(b); //打印ByteBuffer中的byte值 //byte []b1=bb.array(); client.write(output); // output.compact(); //} // text=output.toString(); //System.out.println(text); //output.compact(); } if(key.isWritable()){ client = (SocketChannel) key.channel(); output = (ByteBuffer)key.attachment(); //output.flip(); client.write(output); //output.compact(); } }catch(IOException ex){ key.cancel(); try{ key.channel().close(); }catch(IOException cex){} } } } } } 这是我写的,中间有点乱,因为客户在cmd访问我的服务器如果他输入time,我要给他返回时间。。。大神求助!!
mina框架报异常,数据接收失败
org.apache.mina.filter.codec.ProtocolDecoderException: java.nio.charset.MalformedInputException: Input length = 1 (Hexdump: 23 7B 58 54 3A D3 D0 CE CA CC E2 3B 54 3A 6E 75 6C 6C 3B 56 3A 6E 75 6C 6C 3B 4A 44 3A 6E 75 6C 6C 3B 57 44 3A 6E 75 6C 6C 3B 47 43 3A 6E 75 6C 6C 3B 48 57 3A 30 2E 30 30 3B 48 53 3A 30 2E 30 30 3B 48 46 3A 30 2E 30 30 3B 49 44 30 31 3A 6E 75 6C 6C 3B 53 4A 3A 6E 75 6C 6C 7D 23 0D 0A) at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:180) at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:414) at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:49) at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:832) at org.apache.mina.core.filterchain.IoFilterEvent.fire(IoFilterEvent.java:60) at org.apache.mina.filter.logging.MdcInjectionFilter.filter(MdcInjectionFilter.java:137) at org.apache.mina.filter.util.CommonEventFilter.messageReceived(CommonEventFilter.java:70) at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:414) at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:49) at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:832) at org.apache.mina.core.filterchain.IoFilterEvent.fire(IoFilterEvent.java:60) at org.apache.mina.core.session.IoEvent.run(IoEvent.java:64) at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.runTask(OrderedThreadPoolExecutor.java:551) at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.runTasks(OrderedThreadPoolExecutor.java:543) at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.run(OrderedThreadPoolExecutor.java:487) at java.lang.Thread.run(Unknown Source) Caused by: java.nio.charset.MalformedInputException: Input length = 1 at java.nio.charset.CoderResult.throwException(Unknown Source) at org.apache.mina.core.buffer.AbstractIoBuffer.getString(AbstractIoBuffer.java:1122) at org.apache.mina.filter.codec.textline.TextLineDecoder.decodeAuto(TextLineDecoder.java:207) at org.apache.mina.filter.codec.textline.TextLineDecoder.decode(TextLineDecoder.java:138) at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:170) ... 15 more 2640290 [pool-3-thread-2] WARN com.mina.MinaServerHandler8 - EXCEPTION, please implement com.mina.MinaServerHandler8.exceptionCaught() for proper handling: org.apache.mina.filter.codec.ProtocolDecoderException: java.nio.charset.MalformedInputException: Input length = 1 (Hexdump: 23 7B 58 54 3A D3 D0 CE CA CC E2 3B 54 3A 6E 75 6C 6C 3B 56 3A 6E 75 6C 6C 3B 4A 44 3A 6E 75 6C 6C 3B 57 44 3A 6E 75 6C 6C 3B 47 43 3A 6E 75 6C 6C 3B 48 57 3A 30 2E 30 30 3B 48 53 3A 30 2E 30 30 3B 48 46 3A 30 2E 30 30 3B 49 44 30 31 3A 6E 75 6C 6C 3B 53 4A 3A 6E 75 6C 6C 7D 23 0D 0A) at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:180) at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:414) at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:49) at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:832) at org.apache.mina.core.filterchain.IoFilterEvent.fire(IoFilterEvent.java:60) at org.apache.mina.filter.logging.MdcInjectionFilter.filter(MdcInjectionFilter.java:137) at org.apache.mina.filter.util.CommonEventFilter.messageReceived(CommonEventFilter.java:70) at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:414) at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:49) at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:832) at org.apache.mina.core.filterchain.IoFilterEvent.fire(IoFilterEvent.java:60) at org.apache.mina.core.session.IoEvent.run(IoEvent.java:64) at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.runTask(OrderedThreadPoolExecutor.java:551) at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.runTasks(OrderedThreadPoolExecutor.java:543) at org.apache.mina.filter.executor.OrderedThreadPoolExecutor$Worker.run(OrderedThreadPoolExecutor.java:487) at java.lang.Thread.run(Unknown Source) Caused by: java.nio.charset.MalformedInputException: Input length = 1 at java.nio.charset.CoderResult.throwException(Unknown Source) at org.apache.mina.core.buffer.AbstractIoBuffer.getString(AbstractIoBuffer.java:1122) at org.apache.mina.filter.codec.textline.TextLineDecoder.decodeAuto(TextLineDecoder.java:207) at org.apache.mina.filter.codec.textline.TextLineDecoder.decode(TextLineDecoder.java:138) at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:170) ... 15 more
Apache MINA报这个错应该是什么原因?
org.apache.mina.filter.codec.ProtocolDecoderException: java.nio.charset.MalformedInputException: Input length = 1 (Hexdump: 03 00 00 2F 2A E0 00 00 00 00 00 43 6F 6F 6B 69 65 3A 20 6D 73 74 73 68 61 73 68 3D 41 64 6D 69 6E 69 73 74 72 0D 0A 01 00 08 00 03 00 00 00) at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:235) at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434) at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:46) at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:793) at org.apache.mina.core.filterchain.IoFilterAdapter.messageReceived(IoFilterAdapter.java:119) at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:434) at org.apache.mina.core.filterchain.DefaultIoFilterChain.fireMessageReceived(DefaultIoFilterChain.java:426) at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:638) at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:598) at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:587) at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:61) at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:969) at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: java.nio.charset.MalformedInputException: Input length = 1 at java.nio.charset.CoderResult.throwException(CoderResult.java:281) at org.apache.mina.core.buffer.AbstractIoBuffer.getString(AbstractIoBuffer.java:1442) at org.apache.mina.filter.codec.textline.TextLineDecoder.decodeNormal(TextLineDecoder.java:265) at org.apache.mina.filter.codec.textline.TextLineDecoder.decode(TextLineDecoder.java:139) at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:225) ... 15 more
关于java 实现socket的异步通信
我在网上也找到一个例子,但是没有客户端,我自己写了一个用ServerSocket连的客户端,但是连接上后不能写也不能读,不知道怎么回事,请高手解决。最好能给一个简单异步编程的例子。 下面是代码: package org.scorpion.scoket; /** * * @author chenjd */ import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class NBServer { int port = 8090; int BUFFERSIZE = 1024; Selector selector = null; ServerSocketChannel serverChannel = null; HashMap clientChannelMap = null;// 用来存放每一个客户连接对应的套接字和通道 public NBServer(int port) { this.clientChannelMap = new HashMap(); this.port = port; } public void initialize() throws IOException { // 初始化,分别实例化一个选择器,一个服务器端可选择通道 this.selector = Selector.open(); this.serverChannel = ServerSocketChannel.open(); this.serverChannel.configureBlocking(false); InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress isa = new InetSocketAddress(localhost, this.port); this.serverChannel.socket().bind(isa);// 将该套接字绑定到服务器某一可用端口 } // 结束时释放资源 public void finalize() throws IOException { this.serverChannel.close(); this.selector.close(); } // 将读入字节缓冲的信息解码 public String decode(ByteBuffer byteBuffer) throws CharacterCodingException { Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer charBuffer = decoder.decode(byteBuffer); String result = charBuffer.toString(); return result; } // 监听端口,当通道准备好时进行相应操作 public void portListening(String data) throws IOException, InterruptedException { // 服务器端通道注册OP_ACCEPT事件 SelectionKey acceptKey = this.serverChannel.register(this.selector, SelectionKey.OP_ACCEPT); // 当有已注册的事件发生时,select()返回值将大于0 while (acceptKey.selector().select() > 0) { System.out.println("event happened"); // 取得所有已经准备好的所有选择键 Set readyKeys = this.selector.selectedKeys(); // 使用迭代器对选择键进行轮询 Iterator i = readyKeys.iterator(); while (i.hasNext()) { SelectionKey key = (SelectionKey) i.next(); i.remove();// 删除当前将要处理的选择键 if (key.isAcceptable()) {// 如果是有客户端连接请求 System.out.println("more client connect in!"); ServerSocketChannel nextReady = (ServerSocketChannel) key .channel(); // 获取客户端套接字 Socket s = nextReady.accept().socket(); // 设置对应的通道为异步方式并注册感兴趣事件 s.getChannel().configureBlocking(false); SelectionKey readWriteKey = s.getChannel().register( this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); // 将注册的事件与该套接字联系起来 readWriteKey.attach(s); // 将当前建立连接的客户端套接字及对应的通道存放在哈希表//clientChannelMap中 this.clientChannelMap.put(s, new ClientChInstance(s .getChannel())); } else if (key.isReadable()) {// 如果是通道读准备好事件 System.out.println("Readable"); // 取得选择键对应的通道和套接字 SelectableChannel nextReady = (SelectableChannel) key .channel(); Socket socket = (Socket) key.attachment(); // 处理该事件,处理方法已封装在类ClientChInstance中 this.readFromChannel(socket.getChannel(), (ClientChInstance) this.clientChannelMap .get(socket)); } else if (key.isWritable()) {// 如果是通道写准备好事件 System.out.println("writeable"); // 取得套接字后处理,方法同上 Socket socket = (Socket) key.attachment(); SocketChannel channel = (SocketChannel) socket.getChannel(); // this.writeToChannel(channel, "This is from server!"); this.writeToChannel(channel, data); } } } } // 对通道的写操作 public void writeToChannel(SocketChannel channel, String message) throws IOException { ByteBuffer buf = ByteBuffer.wrap(message.getBytes()); int nbytes = channel.write(buf); } // 对通道的读操作 public void readFromChannel(SocketChannel channel, ClientChInstance clientInstance) throws IOException, InterruptedException { ByteBuffer byteBuffer = null; try{ byteBuffer = ByteBuffer.allocate(BUFFERSIZE); int nbytes = channel.read(byteBuffer); }catch(Exception e){ clientChannelMap.remove(channel.socket()); channel.close(); e=null; return; } byteBuffer.flip(); String result = this.decode(byteBuffer); // 当客户端发出”@exit”退出命令时,关闭其通道 if (result.indexOf("@exit") >= 0||result.indexOf("q")>=0) { channel.close(); } // else if(result.indexOf("@close") >= 0){//关闭服务 // channel.close(); // this.finalize(); // } else { clientInstance.append(result.toString()); // 读入一行完毕,执行相应操作 if (result.indexOf("\n") >= 0) { System.out.println("client input" + result); clientInstance.execute(); } } } // 该类封装了怎样对客户端的通道进行操作,具体实现可以通过重载execute()方法 public class ClientChInstance { SocketChannel channel; StringBuffer buffer = new StringBuffer(); public ClientChInstance(SocketChannel channel) { this.channel = channel; } public void execute() throws IOException { String message = "This is response after reading from channel!"; writeToChannel(this.channel, message); buffer = new StringBuffer(); } // 当一行没有结束时,将当前字窜置于缓冲尾 public void append(String values) { buffer.append(values); } } // 主程序 public static void main(String[] args) { NBServer nbServer = new NBServer(8090); try { nbServer.initialize(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } try { nbServer.portListening("This is from server!"); } catch (Exception e) { e.printStackTrace(); } } } 我写的客户端: package org.scorpion.scoket; import java.io.OutputStream; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws Exception { Socket s = new Socket("172.22.71.146", 8000); OutputStream os = s.getOutputStream(); byte[] by="ksfsksjfklsdjflsdj".getBytes(); os.write(by); s.close(); } }
请求:java写的客户端发送数据失败!!
连接时,给服务端发送数据时总是报错!! 11-28 11:15:36.164: D/MainActivity(4212): wifiname:"LcyAP_03001" prxFlag:true substr: LcyAP FirstConn:true 11-28 11:15:36.164: D/MainActivity(4212): Now Ready to create connect to LC:Now wifi stat is:SSID:"LcyAP_03001"wificonnsetat:trueSrvIp:192.168.173.1 11-28 11:15:36.164: W/System.err(4212): java.net.SocketException: Socket is closed 11-28 11:15:36.174: W/System.err(4212): at java.net.Socket.checkOpenAndCreate(Socket.java:675) 11-28 11:15:36.174: W/System.err(4212): at java.net.Socket.getOutputStream(Socket.java:415) 11-28 11:15:36.174: W/System.err(4212): at cn.LCSys.socket.TCPClient.sendMsg(TCPClient.java:104) 11-28 11:15:36.174: W/System.err(4212): at cn.LCSys.MainActivity$4.run(MainActivity.java:410) 11-28 11:15:36.174: W/System.err(4212): at java.lang.Thread.run(Thread.java:841) 11-28 11:15:38.194: D/MainActivity(4212): wifiname:"LcyAP_03001" prxFlag:true substr: LcyAP FirstConn:true 11-28 11:15:38.194: D/MainActivity(4212): Now Ready to create connect to LC:Now wifi stat is:SSID:"LcyAP_03001"wificonnsetat:trueSrvIp:192.168.173.1 11-28 11:15:38.194: W/System.err(4212): java.net.SocketException: Socket is closed 11-28 11:15:38.194: W/System.err(4212): at java.net.Socket.checkOpenAndCreate(Socket.java:675) 11-28 11:15:38.194: W/System.err(4212): at java.net.Socket.getOutputStream(Socket.java:415) 11-28 11:15:38.194: W/System.err(4212): at cn.LCSys.socket.TCPClient.sendMsg(TCPClient.java:104) 11-28 11:15:38.194: W/System.err(4212): at cn.LCSys.MainActivity$4.run(MainActivity.java:410) 11-28 11:15:38.204: W/System.err(4212): at java.lang.Thread.run(Thread.java:841) 客户端代码为: package cn.LCSys.socket; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import cn.LCSys.MainActivity; import cn.LCSys.fragment.SystemSetting; import android.content.Intent; import android.os.SystemClock; import android.util.Log; public class TCPClient { private String TAG = "TCP Client"; private static TCPClient s_Tcp = null; // 要连接的服务器Ip地址 private String SrvIp; // 要连接的远程服务器在监听的端口 private int SrvPort; public boolean isInitialized = false; private boolean bConnect; Socket socket = null ; private long LastTickCount; public static synchronized TCPClient instance() { if (s_Tcp == null) { { s_Tcp = new TCPClient(Const.SOCKET_SERVER, Const.SOCKET_PORT); } } return s_Tcp; } public TCPClient(String HostIp, int HostListenningPort) { LastTickCount = 0; Log.d(TAG,"SrvIP:["+HostIp+"]SrvPort:["+HostListenningPort+"]."); this.SrvIp = HostIp; this.SrvPort = HostListenningPort; bConnect = false; try { start(); } catch (Exception e) { this.isInitialized = false; Log.d(TAG," TCPClient Initialize catch err!"+e.getMessage()); e.printStackTrace(); } } public static final Object locked = new Object(); public static final BlockingQueue<String> queue = new ArrayBlockingQueue<String>( 1024 * 100); //通过数据接收判断是否链路正常 10秒没有数据认为链路异常,进行重新连接 class EchoThread extends Thread{ private Socket socket; @Override public void run() { while(isInitialized){ try { if(LastTickCount > 0) { //10 if((System.currentTimeMillis() - LastTickCount) > Const.SOCKET_TIMOUT) { bConnect = false; LastTickCount = 0; } } SystemClock.sleep(500); } catch (Exception e) { e.printStackTrace(); } } } } //发送数据 public boolean sendMsg(String sendMsg) throws InterruptedException{ try { PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); pw.write(sendMsg); pw.flush(); return true; } catch (Exception e) { bConnect = false; e.printStackTrace(); return false; } } //} // 接收数据的线程 class ReceiveThread extends Thread { private Socket socket; public ReceiveThread(Socket socket) { this.socket = socket; } @Override public void run() { String receivedString; CharBuffer charBuffer = CharBuffer.allocate(4096); while(isInitialized){ try { Reader reader = new InputStreamReader(socket.getInputStream()); charBuffer.clear(); int index = -1; while((index=reader.read(charBuffer))!=-1) { LastTickCount = System.currentTimeMillis(); charBuffer.flip(); //System.out.println("client:"+charBuffer.toString()); Charset cs = Charset.forName("UTF-8"); receivedString = cs.encode(charBuffer).toString() ; int readlen = receivedString.length(); if( readlen > 100) { //无法获取到数据 /*receivedString = Charset.forName("US-ASCII") .newDecoder().decode(buffer).toString();*/ // mylcHandle.ColldataHandle(receivedString); Log.d(TAG,"Read Data Length: "+readlen); } else { Log.d(TAG, "Recv len:"+readlen+" Content:"+receivedString); } Intent i = new Intent(Const.BC);//广播消息,实现类之间的交互 i.putExtra("response", receivedString); MainActivity.s_context.sendBroadcast(i); //给系统配置广播数据 if(null!= SystemSetting.s_context) { Log.d(TAG, "Broad to SystemSetting:"+readlen); SystemSetting.s_context.sendBroadcast(i); } //给实时数据fragement广播数据 /* if(null!= FragmentRealData.s_context) { Intent ii = new Intent(Const.DATABC); ii.putExtra("response", receivedString); Log.d(TAG, "Broad to FragmentRealData:"+readlen); FragmentRealData.s_context.sendBroadcast(ii); }*/ charBuffer.clear(); } } catch (Exception e) { e.printStackTrace(); } } } } public void start() throws UnknownHostException, IOException{ socket = new Socket(SrvIp,SrvPort); if(socket != null) { bConnect = true; isInitialized = true; new ReceiveThread(socket).start(); } else { bConnect = false; } } boolean isConnect() { return bConnect; } public void closeTCPSocket() { try{ if(socket!= null) { socket.close(); isInitialized = false; } } catch(Exception ex) { Log.e(TAG,"Close Socket error!"); } } // public static void main(String[] args) throws UnknownHostException, IOException { // new TCPClient().start(); // } }
pythonAES加密使用CBC模式与JAVA的CBC加密结果不同!求解!
JAVA的AES加密示例 import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AesUtil { private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; public static String encrypt(String strKey, String strIn) throws Exception { SecretKeySpec skeySpec = getKey(strKey); Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); IvParameterSpec iv = new IvParameterSpec(strKey.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(strIn.getBytes()); String aesResult = new String(Base64.getEncoder().encode(encrypted), StandardCharsets.UTF_8); return aesResult.replace("/", "_"); } private static SecretKeySpec getKey(String strKey) throws Exception { byte[] arrBTmp = strKey.getBytes(); byte[] arrB = new byte[16]; for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } return new SecretKeySpec(arrB, KEY_ALGORITHM); } } 这个是我用python写的AES加密 from Crypto.Cipher import AES import base64 from time import sleep class aescrypt: def __init__(self, key, model, iv, encode_): self.encode_ = encode_ self.model = {'ECB': AES.MODE_ECB, 'CBC': AES.MODE_CBC}[model] self.key = self.add_16(key) if model == 'ECB': self.aes = AES.new(self.key, self.model) # 创建一个aes对象 elif model == 'CBC': self.aes = AES.new(self.key, self.model, iv, segment_size=128) # 创建一个aes对象 elif model == 'CFB': self.aes = AES.new(self.key, self.model) # 这里的密钥长度必须是16、24或32 def add_16(self, par): par = par.encode(self.encode_) while len(par) % 16 != 0: par += b'n' return par def aesencrypt(self, text): # 此处text传入的值为cleartext text = self.add_16(text) print(text) self.encrypt_text = self.aes.encrypt(text) return base64.encodebytes(self.encrypt_text).decode().strip() def aesdecrypt(self, text): text = base64.decodebytes(text.encode(self.encode_)) self.decrypt_text = self.aes.decrypt(text) return self.decrypt_text.decode(self.encode_).strip('\0') if __name__ == '__main__': keyy = input("输入密钥:") cleartext = input("输入明文:") pr = aescrypt(keyy, 'CBC', IV, 'utf8'),此处为加密模式及内容,IV en_text = pr.aesencrypt(cleartext) print('密文:', en_text) print('明文:', pr.aesdecrypt(en_text)) 这里我写了两个加密模式,上述代码已经换成同样的CBC模式加密
Mycat load data infile总是失败,不知道什么原因,求大神解答
mycat采用load data infile方法数据迁移,过程中报错,日志如下: 2017-12-01 11:48:39.919 WARN [$_NIOREACTOR-2-RW] (io.mycat.net.NIOReactor$RW.run(NIOReactor.java:107)) - caught err: java.lang.NullPointerException at io.mycat.net.AbstractConnection.checkWriteBuffer(AbstractConnection.java:456) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.mysql.BinaryPacket.write(BinaryPacket.java:68) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.LoadDataUtil.writeToBackConnection(LoadDataUtil.java:94) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.LoadDataUtil.requestFileDataResponse(LoadDataUtil.java:50) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.handler.MultiNodeQueryHandler.requestDataResponse(MultiNodeQueryHandler.java:734) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.MySQLConnectionHandler.handleRequestPacket(MySQLConnectionHandler.java:179) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.MySQLConnectionHandler.handleData(MySQLConnectionHandler.java:101) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.handler.BackendAsyncHandler.offerData(BackendAsyncHandler.java:36) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.MySQLConnectionHandler.handle(MySQLConnectionHandler.java:80) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.handle(AbstractConnection.java:263) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.onReadData(AbstractConnection.java:321) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.NIOSocketWR.asynRead(NIOSocketWR.java:190) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.asynRead(AbstractConnection.java:273) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.NIOReactor$RW.run(NIOReactor.java:102) ~[Mycat-server-1.6-RELEASE.jar:?] at java.lang.Thread.run(Thread.java:745) [?:1.7.0_80] 2017-12-01 11:48:39.948 INFO [$_NIOREACTOR-2-RW] (io.mycat.net.AbstractConnection.close(AbstractConnection.java:508)) - close connection,reason:program err:java.lang.NullPointerException ,MySQLConnection [id=6, lastTime=1512100119275, user=root, schema=log_db_2017-11, old shema=log_db_2017-11, borrowed=true, fromSlaveDB=false, threadId=58, charset=gbk, txIsolation=3, autocommit=true, attachment=dn8{LOAD DATA LOCAL INFILE 'C:\\Users\\User\\Desktop\\log_file_manage_4-9.txt' INTO TABLE log_file_manage CHARACTER SET 'utf8' COLUMNS ESCAPED BY '%' (`uuid`, `client_number`, `customer_id`, `decode_flag`, `analysis_flag`, `file_name`, `file_path`, `upload_time`, `sys_number`, `sys_name`, `sys_path`, `sys_version`, `result`, `operate_time`, `line_begin`, `line_end`, `vdi_info`)}, respHandler=io.mycat.backend.mysql.nio.handler.MultiNodeQueryHandler@4c156b4b, host=localhost, port=3306, statusSync=io.mycat.backend.mysql.nio.MySQLConnection$StatusSync@12372ff3, writeQueue=0, modifiedSQLExecuted=true] 2017-12-01 11:48:40.254 WARN [$_NIOREACTOR-2-RW] (io.mycat.net.NIOReactor$RW.run(NIOReactor.java:107)) - caught err: java.lang.NullPointerException at io.mycat.net.AbstractConnection.writeToBuffer(AbstractConnection.java:475) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.write(AbstractConnection.java:417) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.LoadDataUtil.requestFileDataResponse(LoadDataUtil.java:62) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.handler.MultiNodeQueryHandler.requestDataResponse(MultiNodeQueryHandler.java:734) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.MySQLConnectionHandler.handleRequestPacket(MySQLConnectionHandler.java:179) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.MySQLConnectionHandler.handleData(MySQLConnectionHandler.java:101) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.handler.BackendAsyncHandler.offerData(BackendAsyncHandler.java:36) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.backend.mysql.nio.MySQLConnectionHandler.handle(MySQLConnectionHandler.java:80) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.handle(AbstractConnection.java:263) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.onReadData(AbstractConnection.java:321) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.NIOSocketWR.asynRead(NIOSocketWR.java:190) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.AbstractConnection.asynRead(AbstractConnection.java:273) ~[Mycat-server-1.6-RELEASE.jar:?] at io.mycat.net.NIOReactor$RW.run(NIOReactor.java:102) ~[Mycat-server-1.6-RELEASE.jar:?] at java.lang.Thread.run(Thread.java:745) [?:1.7.0_80] 哪位大神能帮忙看看,不尽感谢。
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
【JSON解析】浅谈JSONObject的使用
简介 在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于语言的文本格式,这使得Json成为理想的数据交换语言。 JSON建构于两种结构: “名称/值”对的集合(A Collection of name/va...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
一名大专同学的四个问题
【前言】   收到一封来信,赶上各种事情拖了几日,利用今天要放下工作的时机,做个回复。   2020年到了,就以这一封信,作为开年标志吧。 【正文】   您好,我是一名现在有很多困惑的大二学生。有一些问题想要向您请教。   先说一下我的基本情况,高考失利,不想复读,来到广州一所大专读计算机应用技术专业。学校是偏艺术类的,计算机专业没有实验室更不用说工作室了。而且学校的学风也不好。但我很想在计算机领...
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
世界上有哪些代码量很少,但很牛逼很经典的算法或项目案例?
点击上方蓝字设为星标下面开始今天的学习~今天分享四个代码量很少,但很牛逼很经典的算法或项目案例。1、no code 项目地址:https://github.com/kelseyhight...
立即提问