network.java
来自「自己写的轮询提问的小程序 新手刚学 多多指教 合乎哈」· Java 代码 · 共 102 行
JAVA
102 行
/*This is the network class of the PollServer. It handles all the network stuffCopyright (C) 2005-2006 Igor Partola, Michael J. Krikonis, Clark UniversityThis program is free software; you can redistribute it and/ormodify it under the terms of the GNU General Public Licenseas published by the Free Software Foundation; either version 2of the License, or (at your option) any later version.This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with this program; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.*/package SharedClasses;import java.net.*;import java.io.*; public class Network { public final static int BUFFER_SIZE = 4096*4; private InputStream in; private OutputStream out; private Socket clntSock; public final static byte CLIENT_DISCONNECTED = 10; public final static byte CHECK_BYTE = 0; public final static byte SERVER_SENDING_QUESTION = 1; public final static byte CLIENT_SENDING_ANSWER = 100; public final static byte QUESTION_CLOSED = 11; public Network(Socket c) { clntSock = c; try { in = clntSock.getInputStream(); out = clntSock.getOutputStream(); } catch (IOException e) { System.out.println("Client disconnected prematurely"); } } public boolean askQuestion(Question q) { if (q == null) return false; byte[] buf = q.getBytes(); try { out.write(SERVER_SENDING_QUESTION); out.write(buf); } catch (IOException e) { return false; } return true; } public boolean closeQuestion() { try { out.write(QUESTION_CLOSED); } catch (IOException e) { return false; } return true; } public int checkForAnswer() { byte[] b = new byte[1]; try { if (in.read(b) > 0) return (int) b[0]; } catch (IOException e) { return -1; } return -1; } public boolean ping() { byte[] b = new byte[1]; b[0] = CHECK_BYTE; try { out.write(b); if (in.read(b) > 0) return true; } catch (IOException e) { return false; } return false; } public void close() { try { clntSock.close(); } catch (IOException e) { } } }
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?