📄 talkthread.java
字号:
/*TalkThread is the thread class that talks to the clients (asks questions, etc).Copyright (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 PollServer;import java.net.*;import java.io.*;import SharedClasses.*;class TalkThread implements Runnable { private Network myNet; private Thread t; private PollServerThread parent; private Question currentQuestion = null; private boolean endOfLife = false; private int status = 0; private static final int QUESTION_CLOSED = -2; private final static int BUFFER_SIZE = 4*4096; TalkThread(Socket c, PollServerThread p) { myNet = new Network(c); parent = p; parent.getParent().addTalkThread(this); } public void start() { t = new Thread(this); t.start(); } private void waitForQuestion() { int pingCount = 0; try { while (true) { t.sleep (50); if (currentQuestion != null) { myNet.askQuestion(currentQuestion); currentQuestion = null; return; } pingCount++; if (pingCount > 15) { if (!myNet.ping()) { endOfLife = true; return; } pingCount = 0; } } } catch (InterruptedException e) {endOfLife = true;} } private int waitForAnswer(){ int answer = -1; int tmp_answer = -1; int pingCount = 0; try { while (status != QUESTION_CLOSED) { t.sleep (50); tmp_answer = myNet.checkForAnswer(); if (tmp_answer >= 0) answer = tmp_answer; pingCount++; if (pingCount > 15) { if (!myNet.ping()) { endOfLife = true; return answer; } pingCount = 0; } } } catch (InterruptedException e) {endOfLife = true;} return answer; } public void run() { int answer; while (true) { if (endOfLife) break; status = 0; currentQuestion = null; waitForQuestion(); if (endOfLife) break; answer = waitForAnswer(); if (!endOfLife) { myNet.closeQuestion(); if (answer >= 0) parent.getParent().updateVotes(answer); answer = -1; } else { if (answer >= 0) parent.getParent().updateVotes(answer); answer = -1; break; } } stop(); } public void setQuestion(Question q) { currentQuestion = q; } public void stop() { myNet.close(); endOfLife = true; parent.getParent().removeTalkThread(this); t = null; } public void closeQuestion() { status = QUESTION_CLOSED; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -