服务器端程序接受连接并处理客户端的请求
ServerAppjava
package test;
import javaio*;
import javanet*;
/** *//**
* 服务器端程序
*
* @author luxuan修正赵学庆
*
*/
public class ServerApp {
static final int PORT = ;
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader netIn;
private PrintWriter netOut;
public ServerApp() throws IOException {
serverSocket = new ServerSocket(PORT); xxxxcom
Systemoutprintln(server start);
while (true) {
// 等待连接
socket = serverSocketaccept();
ServerThread st = new ServerThread(socket);
new Thread(st)start();
}
}
class ServerThread implements Runnable {
private Socket socket;
private int randomNumber;
private int clientGuessNumber;
public ServerThread(Socket s) throws IOException {
socket = s;
xxxcom
netIn = new BufferedReader(new InputStreamReader(socketgetInputStream()));
netOut = new PrintWriter(socketgetOutputStream());
}
public void run() {
Systemoutprintln(client + socketgetInetAddress() + is connect);
randomNumber = (int) (Mathrandom() * );
Systemoutprintln(random number is: + randomNumber);
try {
clientGuessNumber = IntegerparseInt(netInreadLine());
Systemoutprintln(client guess number is: + clientGuessNumber);
xxxx
for (int i = ; i > ; i) {
if (clientGuessNumber == randomNumber) {
netOutprintln(OK恭喜猜对了);
ClientAppfinished = true;
} else if (clientGuessNumber < randomNumber) {
netOutprintln(您猜的数小了您还有 + (i ) + 次机会);
ClientAppfinished = false;
} else if (clientGuessNumber > randomNumber) { xxxcom
netOutprintln(您猜的数大了您还有 + (i ) + 次机会);
ClientAppfinished = false;
}
netOutflush();
if (!ClientAppfinished) {
clientGuessNumber = IntegerparseInt(netInreadLine());
} else {
break;
}
} xxxx
if (!ClientAppfinished) {
netOutprintln(OK您没有机会了游戏结束);
}
ClientAppfinished = true;
} catch (IOException e) {
} finally {
try {
netOutclose();
netInclose();
socketclose();
} catch (IOException ee) { xxxxxx@com
}
}
}
}
public static void main(String[] args) throws IOException {
new ServerApp();
}
}
[] []