ServerApp
package test;
import java
import
/** *//**
* 服務器端程序
*
* @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);
System
while (true)
// 等待連接
socket = serverSocket
ServerThread st = new ServerThread(socket);
new Thread(st)
}
}
class ServerThread implements Runnable
private Socket socket;
private int randomNumber;
private int clientGuessNumber;
public ServerThread(Socket s) throws IOException
socket = s;
netIn = new BufferedReader(new InputStreamReader(socket
netOut = new PrintWriter(socket
}
public void run()
System
randomNumber = (int) (Math
System
try
clientGuessNumber = Integer
System
for (int i =
if (clientGuessNumber == randomNumber)
netOut
ClientApp
} else if (clientGuessNumber < randomNumber)
netOut
ClientApp
} else if (clientGuessNumber > randomNumber)
netOut
ClientApp
}
netOut
if (!ClientApp
clientGuessNumber = Integer
} else
break;
}
}
if (!ClientApp
netOut
}
ClientApp
} catch (IOException e)
} finally
try
netOut
netIn
socket
} catch (IOException ee)
}
}
}
}
public static void main(String[] args) throws IOException
new ServerApp();
}
}
package test;
import java
import
public class ClientApp
private Socket socket;
private BufferedReader netIn;
private PrintWriter netOut;
private BufferedReader keyboardIn;
static Boolean finished = false;
public ClientApp() throws IOException
System
keyboardIn = new BufferedReader(new InputStreamReader(System
try
if (keyboardIn
socket = new Socket(InetAddress
} else
socket = new Socket(InetAddress
}
netIn = new BufferedReader(new InputStreamReader(socket
netOut = new PrintWriter(socket
} catch (UnknownHostException e)
System
System
}
System
while (!finished)
System
netOut
netOut
String str = netIn
if (str == null)
finished = true;
break;
}
System
if (str
finished = true;
break;
}
}
netIn
netOut
keyboardIn
socket
}
public static void main(String[] args) throws IOException
new ClientApp();
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27387.html