C/S 应用入门实践
我们工作实基于B/S架构的,前几天同学有个C/S的作业,内容大致如下:
做一个C/S模式的程序,比如说猜价格游戏,猜低了,服务器告诉你低了,猜高了,服务器告诉你低了,猜中了,服务器恭喜你。
第一次,我没什么时间,就干脆写了个脚本;这东西为啥用服务器,东北话:要啥自行车!!!
脚本代码如下:
<html>
<HEAD>
<TITLE>随即测试</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"></HEAD>
<style>
.testClass
{
Color:green;
Font:bold 18pt Arial
}
</style>
<table>
<tr>
<td class="testClass">hello</td>
<!--
<td><input type="text" name="some" onChange="checkIDNum(this.value);"/></td>
-->
<td nowrap><input type="text" class="testClass" size="60" name="some" id="some" onChange="checkNum(this.value);" style="display:block"/></td>
</tr>
<tr>
<td height="20"></td><td></td>
</tr>
<tr>
<td nowrap colspan="2"><INPUT type="text" class="testClass" size="60" name="cc" id="cc" readonly="readonly" style="display:none"> </td>
</tr>
<tr>
<td height="20"></td><td></td>
</tr>
<tr>
<td nowrap colspan="2"><INPUT type="text" class="testClass" size="20" name="vv" id="vv" readonly="readonly" style="display:none"> </td>
</tr>
</table>
<script language="Javascript">
var count = 0;
function checkNum(str){
var a = 500;
var ran = Math.random();
var foot = Math.round(ran * (a-1))+1;
var inputInfo = document.getElementById("vv");
inputInfo.value = 正确结果是:'+ foot;
inputInfo.style.display = "block";
if(str != foot){
var inputInfo = document.getElementById("some");
inputInfo.value = '';
inputInfo.style.display = "none";
var inputcc = document.getElementById("cc");
inputcc.value = 'You are input failure! HaHa ! please refresh this page!';
inputcc.style.display = "block";
}
if(str == foot){
if( confirm("You are input success! try it again ?") ) {
var inputInfo = document.getElementById("some");
inputInfo.value = 'please input 0~500 number again,good luck';
var inputcc = document.getElementById("cc");
count++;
inputcc.value = 'You are input success! ' + count + '´Î';
inputcc.style.display = "block";
}
}
}
document.writeln("这是Javascript!采用直接插入的方法!");
</script>
<html>
看上去也差不多,同学说,老师不干,无奈,只好重新做个浪费时间的东西!
下面使用C/S写的,代码如下:
package knockwork;
import java.io.*;
import java.net.*;
/*
* add by Kevin.Wang in shangHai
*/
public class MyClient {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket("localhost", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
//上面这个是客户端应用程序
package knockwork;
import java.net.*;
import java.io.*;
/*
* add by Kevin.Wang in shangHai
*/
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
MyBusinessProtocol kkp = new MyBusinessProtocol();
outputLine = kkp.processInput(null,0);
out.println(outputLine);
int clientBid = 0;
while ((inputLine = in.readLine()) != null) {
try{
clientBid = Integer.parseInt(inputLine.trim());
}catch(NumberFormatException e){
out.println("You must input int type data , please rewrite !");
continue;
}
outputLine = kkp.processInput(inputLine,clientBid);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
//上面这个是服务器运行程序
package knockwork;
import java.util.Random;
/*
* add by Kevin.Wang in shangHai
*/
public class MyBusinessProtocol {
private static final int FIRST = 0;
private static final int WAITING = 1;
//private static final int LOWER = 2;
//private static final int HIGHER = 3;
//private static final int OK = 4;
private static final int SELECT = 5;
private static final int ANOTHER = 6;
private static final int EXIT = 10;
private int state = FIRST;
private int totalSpent = 0;
private int currentBid = 0;
private int realValue = 0;
private StringBuffer itemBuffer = new StringBuffer();
private String[] items = {"apple","joybook","pen","xylitol","mouse"};
private int joke = 0;
/*
* main business method
*/
public String processInput(String theInput,int clientBid) {
String theOutput = null;
if (state == FIRST) {//-----------------------------------------
initRealValue();
theOutput = "Hello, this is a [ "+items[joke]+
" ] Please bid ! Good Luck !";
state = WAITING;
}else if(state == WAITING){//-----------------------------------
if(clientBid>=0 && clientBid <= 500){
totalSpent += clientBid;
}
if(clientBid < 0 || clientBid > 500){
theOutput = "OK! Yor are right! Congratulation ! " +
"You have spent ="+totalSpent +
"! You have obtain :"+itemBuffer.toString()+
"; Want another? (0/1)";
state = ANOTHER;
//TODO have obtain item
}
if(clientBid < realValue){
theOutput = "Lower!";
}else if(clientBid > realValue){
theOutput = "Higher!";
}else if (clientBid == realValue){
if(itemBuffer.length() > 0){
itemBuffer.append(" , ");
}
itemBuffer.append(items[joke]);
theOutput = "OK! Yor are right! Congratulation ! " +
"You have spent ="+totalSpent +
"! You have obtain :"+itemBuffer.toString()+
"; Want another? (0/1)";
//TODO have obtain item
state = ANOTHER;
}
}else if (state == SELECT){//------------------------------------
theOutput = "Want another? (0/1)";
state = ANOTHER;
}else if (state == ANOTHER){//-----------------------------------
if (clientBid == 1) {
theOutput = "Hello, this is a [ "+items[joke]+
" ] Please bid ! Good Luck !";
state = WAITING;
initRealValue();
if(joke >= 4){
joke = 0;
}else {
joke++;
}
}else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
/*
* 随即计算
*/
private int testRandom(){
int num = 500;
Random random = new Random();
int a = random.nextInt(num);
//System.out.println("a="+a);
return a;
}
public int getRealValue() {
return realValue;
}
public void initRealValue() {
this.realValue = testRandom();
}
}
//这个是服务器用的业务逻辑
因为我没有服务器,都在自己及其上用的,所以host用localhost
运行方式:先运行MyServer,再运行MyClient,然后就会出现
"Hello, this is a [ apple] Please bid ! Good Luck !"
你就可以出价[0~500],自己运行玩玩吧。