java

位置:IT落伍者 >> java >> 浏览文章

Java多线程Socket操作猜数游戏样例[1]


发布日期:2018年09月30日
 
Java多线程Socket操作猜数游戏样例[1]

服务器端程序接受连接并处理客户端的请求

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();

}

}

[] []

               

上一篇:Java多线程Socket操作猜数游戏样例[2]

下一篇:超线程多核心下Java多线程编程技术分析[4]