涉及到的内容
1、项目框架设计
2、java面向对象编程
3、网络编程
4、多线程
5、IO流
6、Mysql / 使用集合充当内存数据库
项目开发流程简介
1、需求分析
- 需求分析师:懂技术+行业
- 出一个需求分析报告(白皮书),该项目功能,客户具体要求
2、设计阶段
- 架构师 / 项目经理
- 设计工作(UML类图,流程图,模块设计,数据库,架构)
- 原型开发
- 组建团队
3、编码阶段
- 程序员 / 码农
- 完成架构师的模块功能
- 测试自己的模块
4、测试阶段
- 测试工程师
- 单元测试,测试用例,白盒测试,黑盒测试,集成测试
5、实施阶段
- 实施工程师(开发能力 / 环境配置部署能力)
- 项目正确的部署到客户的平台,并保证运行正常
- 身体好 _
6、维护阶段
需求分析
1、用户登录 2、拉取在线用户 3、无异常退出(客户端、服务端) 4、私聊 5、群发 6、发文件 7、服务器推送新闻
客户端界面设计
程序框架图
代码实现
服务端
Message.java
package com.leaveriver.common;
import java.io.Serializable;
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
private String sender;
private String getter;
private String content;
private String senderTime;
private String mesType;
private byte[] fileBytes;
private int fileLen = 0;
private String srcFilePath;
private String destFilePath;
public byte[] getFileBytes() {
return fileBytes;
}
public void setFileBytes(byte[] fileBytes) {
this.fileBytes = fileBytes;
}
public int getFileLen() {
return fileLen;
}
public void setFileLen(int fileLen) {
this.fileLen = fileLen;
}
public String getSrcFilePath() {
return srcFilePath;
}
public void setSrcFilePath(String srcFilePath) {
this.srcFilePath = srcFilePath;
}
public String getDestFilePath() {
return destFilePath;
}
public void setDestFilePath(String destFilePath) {
this.destFilePath = destFilePath;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getGetter() {
return getter;
}
public void setGetter(String getter) {
this.getter = getter;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSenderTime() {
return senderTime;
}
public void setSenderTime(String senderTime) {
this.senderTime = senderTime;
}
public String getMesType() {
return mesType;
}
public void setMesType(String mesType) {
this.mesType = mesType;
}
}
MessageType.java
package com.leaveriver.common;
public interface MessageType {
String MESSAGE_LOGIN_SUCCEED = "1" ;
String MESSAGE_LOGIN_FAILED = "2" ;
String MESSAGE_COMM_MES = "3" ;
String MESSAGE_GET_ONLINE_FRIEND = "4" ;
String MESSAGE_RET_ONLINE_FRIEND = "5" ;
String MESSAGE_CLIENT_EXIT = "6" ;
String MESSAGE_TO_ALL_MES = "7";
String MESSAGE_FILE_OUTPUT = "8";
String MESSAGE_SERVER_MES = "9";
}
User.java
package com.leaveriver.common;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String userID ;
private String password;
public User() {
}
public User(String userID, String password) {
this.userID = userID;
this.password = password;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
ManageServerConnectClientThread .java
package com.leaveriver.service;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ManageServerConnectClientThread {
private static HashMap<String, ServerConnectClientThread> hashMap = new HashMap<>();
public static boolean getOnline(String userId) {
return hashMap.containsKey(userId);
}
public static HashMap<String, ServerConnectClientThread> getHashMap() {
return hashMap;
}
public static void addServerConnectClientThread(
String userId, ServerConnectClientThread serverConnectClientThread) {
hashMap.put(userId, serverConnectClientThread);
}
public static ServerConnectClientThread getServerConnectClientThread(String userId){
return hashMap.get(userId);
}
public static String getOnlineUser(){
Iterator<String> iterator = hashMap.keySet().iterator();
String onlineUserList = "";
while (iterator.hasNext()) {
onlineUserList += iterator.next().toString() + " " ;
}
return onlineUserList;
}
public static void removeServerConnectClientThread(String userId){
hashMap.remove(userId);
}
}
ManageUsers .java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class ManageUsers {
private static ConcurrentHashMap<String, ArrayList<Message>> offLineDb = new ConcurrentHashMap<>();
private static HashMap<String, User> validUsers = new HashMap<>();
static {
validUsers.put("100", new User("100", "123456"));
validUsers.put("200", new User("200", "123456"));
validUsers.put("300", new User("300", "123456"));
validUsers.put("至尊宝", new User("至尊宝", "123456"));
validUsers.put("紫霞仙子", new User("紫霞仙子", "123456"));
}
public static User get(String userId){
return validUsers.get(userId);
}
public static void addOffLineDb(String getter, ArrayList<Message> message) {
offLineDb.put(getter, message);
}
public static ArrayList<Message> getOffLineDb(String getter){
return offLineDb.get(getter);
}
public static boolean containsOffLineDb(String getter) {
return offLineDb.containsKey(getter);
}
public static void removeOffLineDb(String getter) {
offLineDb.remove(getter);
}
}
PushMesServerService .java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import com.leaveriver.utils.Utility;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
public class PushMesServerService extends Thread {
@Override
public void run() {
while (true) {
System.out.println("请输入你要推送的消息:");
String newsMes = Utility.readString(100);
Message message = new Message();
message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
message.setSender("服务器");
message.setContent(newsMes);
message.setSenderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
HashMap<String, ServerConnectClientThread> hashMap = ManageServerConnectClientThread.getHashMap();
Iterator<String> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
String next = iterator.next();
try {
OutputStream os = hashMap.get(next).getSocket().getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(message);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("[服务器推送记录][" + message.getSenderTime() + "]" +
message.getSender() + "推送信息:" + newsMes);
}
}
}
ServerConnectClientThread.java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class ServerConnectClientThread extends Thread {
private Socket socket;
private String userId;
public ServerConnectClientThread(Socket socket, String userId) {
this.socket = socket;
this.userId = userId;
}
public Socket getSocket() {
return socket;
}
@Override
public void run() {
while (true) {
try {
System.out.println("服务器和客户端[" + userId + "]保持通信,读取数据。。。。");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message message = (Message) ois.readObject();
if (!ManageServerConnectClientThread.getOnline(message.getGetter()) && (ManageUsers.get(message.getGetter()) != null)) {
if (!ManageUsers.containsOffLineDb(message.getGetter())) {
ArrayList<Message> arrayList = new ArrayList<>();
arrayList.add(message);
ManageUsers.addOffLineDb(message.getGetter(), arrayList);
} else {
ArrayList<Message> offLineDb = ManageUsers.getOffLineDb(message.getGetter());
offLineDb.add(message);
ManageUsers.addOffLineDb(message.getGetter(), offLineDb);
}
if (message.getMesType().equals(MessageType.MESSAGE_FILE_OUTPUT)) {
System.out.println("[离线文件记录][" + message.getSenderTime() + "]" +
message.getSender() + "发送文件给" + message.getGetter() + "\n" +
message.getSrcFilePath() + " 到 " + message.getDestFilePath());
} else {
System.out.println("[离线消息记录][" + message.getSenderTime() + "]" +
message.getSender() + " 对 " + message.getGetter() + "说: " + message.getContent());
}
} else {
if (message.getMesType().equals(MessageType.MESSAGE_GET_ONLINE_FRIEND)) {
System.out.println(message.getSender() + "要获取在线用户");
String onlineUser = ManageServerConnectClientThread.getOnlineUser();
Message mes = new Message();
mes.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
mes.setContent(onlineUser);
mes.setGetter(mes.getSender());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(mes);
} else if (message.getMesType().equals(MessageType.MESSAGE_CLIENT_EXIT)) {
System.out.println(message.getSender() + "退出");
ManageServerConnectClientThread.removeServerConnectClientThread(message.getSender());
socket.close();
break;
} else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {
System.out.println("[私聊记录][" + message.getSenderTime() + "]" +
message.getSender() + " 对 " + message.getGetter() + "说: " + message.getContent());
ServerConnectClientThread scct = ManageServerConnectClientThread.getServerConnectClientThread(message.getGetter());
ObjectOutputStream oos = new ObjectOutputStream(scct.getSocket().getOutputStream());
oos.writeObject(message);
} else if (message.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)) {
System.out.println("[群聊消息记录][" + message.getSenderTime() + "]" +
message.getSender() + " 对大家说: " + message.getContent());
HashMap<String, ServerConnectClientThread> hashMap = ManageServerConnectClientThread.getHashMap();
Iterator<String> iterator = hashMap.keySet().iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (!next.equals(message.getSender())) {
OutputStream os = hashMap.get(next).getSocket().getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(message);
}
}
} else if (message.getMesType().equals(MessageType.MESSAGE_FILE_OUTPUT)) {
System.out.println("[文件传输记录][" + message.getSenderTime() + "]" +
message.getSender() + "发送文件给" + message.getGetter() + "\n" +
message.getSrcFilePath() + " 到 " + message.getDestFilePath());
ServerConnectClientThread scct = ManageServerConnectClientThread.getServerConnectClientThread(message.getGetter());
OutputStream os = scct.getSocket().getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(message);
} else {
System.out.println("其他类型暂时不处理");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ServerService.java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import com.leaveriver.common.User;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class ServerService {
private ServerSocket serverSocket;
private boolean checkUser(String userId, String password) {
User user = ManageUsers.get(userId);
if (user == null)
return false;
if (!user.getPassword().equals(password))
return false;
return true;
}
public ServerService() {
try {
System.out.println("服务端在9999端口监听。");
new PushMesServerService().start();
serverSocket = new ServerSocket(9999);
while (true) {
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
User user = (User) ois.readObject();
Message message = new Message();
if (checkUser(user.getUserID(), user.getPassword())) {
message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
oos.writeObject(message);
ServerConnectClientThread scct = new ServerConnectClientThread(socket, user.getUserID());
scct.start();
ManageServerConnectClientThread.addServerConnectClientThread(user.getUserID(), scct);
ArrayList<Message> offLineDb = ManageUsers.getOffLineDb(user.getUserID());
if (offLineDb != null)
for (int i = 0; i < offLineDb.size() ; i++) {
Message mes = offLineDb.get(i);
OutputStream outputStream = ManageServerConnectClientThread.getServerConnectClientThread(mes.getGetter()).getSocket().getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(mes);
objectOutputStream.flush();
ManageUsers.removeOffLineDb(mes.getGetter());
}
} else {
message.setMesType(MessageType.MESSAGE_LOGIN_FAILED);
oos.writeObject(message);
socket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Utility.java
package com.leaveriver.utils;
import java.util.Scanner;
public class Utility {
private static Scanner scanner = new Scanner(System.in);
public static char readMenuSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1, false);
c = str.charAt(0);
if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5') {
System.out.println("选择错误,请重新输入:");
} else break;
}
return c;
}
public static char readChar() {
String str = readKeyBoard(1, false);
return str.charAt(0);
}
public static char readChar(char defaultValue) {
String str = readKeyBoard(1, true);
return str.length() == 0 ? defaultValue : str.charAt(0);
}
public static int readInt() {
int n;
for (; ; ) {
String str = readKeyBoard(2, false);
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.println("选择错误,请重新输入:");
}
}
return n;
}
public static int readInt(int defaultValue) {
int n;
for (; ; ) {
String str = readKeyBoard(2, false);
if (str.equals("")) {
return defaultValue;
}
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.println("选择错误,请重新输入:");
}
}
return n;
}
public static String readString(int limit) {
return readKeyBoard(limit, false);
}
public static String readString(int limit, String defaultValue) {
String str = readKeyBoard(limit, true);
return str.equals("") ? defaultValue : str;
}
public static char readConfirmSelection() {
System.out.println("请输入你的选择(Y/N)");
char c;
for (; ; ) {
String str = readKeyBoard(1, false).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'N') {
break;
} else {
System.out.print("选择错误,请重新输入:");
}
}
return c;
}
private static String readKeyBoard(int limit, boolean blankReturn){
String line="";
while (scanner.hasNextLine()){
line=scanner.nextLine();
if(line.length()==0){
if(blankReturn) return line;
else continue;
}
if(line.length()<1 || line.length()>limit){
System.out.println("输入长度(不大于 "+ limit + ")错误,请重新输入:");
continue;
}
break;
}
return line;
}
}
QQFrame.java
package com.leaveriver.qqframe;
import com.leaveriver.service.ServerService;
public class QQFrame {
public static void main(String[] args) {
new ServerService();
}
}
客户端
ClientConnectServerThread .java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import com.leaveriver.utils.Utility;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
public class ClientConnectServerThread extends Thread {
private Socket socket;
public ClientConnectServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
while (true) {
try {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message message = (Message) ois.readObject();
if (message.getMesType().equals(MessageType.MESSAGE_RET_ONLINE_FRIEND)) {
String[] s = message.getContent().split(" ");
System.out.println("\n============当前在线用户列表=================");
for (int i = 0; i < s.length; i++) {
System.out.println("用户: " + s[i]);
}
} else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {
System.out.println("\n [" + message.getSenderTime() + "] " + message.getSender() + "对你说: " + message.getContent());
} else if (message.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)) {
System.out.println("\n [" + message.getSenderTime() + "] " + message.getSender() + "对大家说: " + message.getContent());
} else if (message.getMesType().equals(MessageType.MESSAGE_SERVER_MES)) {
System.out.println("\n [" + message.getSenderTime() + "] " + message.getSender() + "对大家说: " + message.getContent());
} else if (message.getMesType().equals(MessageType.MESSAGE_FILE_OUTPUT)) {
FileOutputStream fos = new FileOutputStream(message.getDestFilePath());
fos.write(message.getFileBytes());
fos.flush();
System.out.println("\n" + message.getSender() + "给你发送文件,保存在:" + message.getDestFilePath() + "路径");
System.out.println("保存成功");
fos.close();
} else {
System.out.println("其他类型的信息, 这里暂时不处理");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Socket getSocket() {
return socket;
}
}
FileService .java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import com.leaveriver.utils.StreamUtils;
import java.io.*;
import java.text.SimpleDateFormat;
public class FileService {
public void sendFile(String sender, String fileToUser, String srcFilePath, String destFilePath){
Message message = new Message();
message.setSender(sender);
message.setGetter(fileToUser);
message.setMesType(MessageType.MESSAGE_FILE_OUTPUT);
message.setSrcFilePath(srcFilePath);
message.setDestFilePath(destFilePath);
message.setSenderTime(new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
FileInputStream fis = null;
byte[] fileBytes;
try {
fis = new FileInputStream(srcFilePath);
fileBytes = new byte[(int) new File(srcFilePath).length()];
fis.read(fileBytes);
message.setFileBytes(fileBytes);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
ObjectOutputStream oos = new ObjectOutputStream(
ManageClientConnetServerThread.getClientConnectServerThread(sender).getSocket().getOutputStream());
oos.writeObject(message);
System.out.println("文件发送完成===");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ManageClientConnetServerThread .java
package com.leaveriver.service;
import jdk.nashorn.internal.ir.CallNode;
import java.util.HashMap;
public class ManageClientConnetServerThread {
private static HashMap<String, ClientConnectServerThread> hashMap = new HashMap<>();
public static void addClientConnectServerThread(
String userId, ClientConnectServerThread clientConnectServerThread){
hashMap.put(userId,clientConnectServerThread);
}
public static ClientConnectServerThread getClientConnectServerThread(String userId) {
return hashMap.get(userId);
}
}
MessageService .java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import com.leaveriver.common.User;
import com.leaveriver.utils.StreamUtils;
import com.leaveriver.utils.Utility;
import java.io.*;
import java.net.Socket;
import java.text.SimpleDateFormat;
public class MessageService {
public void userOneChat(String senderId, String chatContent, String chatToUserId) {
Message message = new Message();
message.setMesType(MessageType.MESSAGE_COMM_MES);
message.setSender(senderId);
message.setGetter(chatToUserId);
message.setContent(chatContent);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
message.setSenderTime(df.format(System.currentTimeMillis()));
try {
ClientConnectServerThread ccst = ManageClientConnetServerThread.getClientConnectServerThread(senderId);
OutputStream os = ccst.getSocket().getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(message);
System.out.println("私聊内容发送成功");
} catch (IOException e) {
e.printStackTrace();
}
}
public void chatAllUsers(String sender, String content) {
Message message = new Message();
message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
message.setSender(sender);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
message.setSenderTime(df.format(System.currentTimeMillis()));
message.setContent(content);
try {
ObjectOutputStream oos = new ObjectOutputStream(
ManageClientConnetServerThread.getClientConnectServerThread(sender).getSocket().getOutputStream());
oos.writeObject(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserClientService .java
package com.leaveriver.service;
import com.leaveriver.common.Message;
import com.leaveriver.common.MessageType;
import com.leaveriver.common.User;
import com.leaveriver.utils.Utility;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
public class UserClientService {
private User user = new User();
private Socket socket;
public boolean checkUser(String userId, String password) {
boolean b = false;
user.setUserID(userId);
user.setPassword(password);
try {
socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(user);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message message = (Message) ois.readObject();
if (message.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) {
ClientConnectServerThread ccst = new ClientConnectServerThread(socket);
ccst.start();
ManageClientConnetServerThread.addClientConnectServerThread(userId, ccst);
b = true;
} else {
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
public void onlineFriendList(){
Message message = new Message();
message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
message.setSender(user.getUserID());
try {
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public void systemExit(){
Message message = new Message();
message.setMesType(MessageType.MESSAGE_CLIENT_EXIT);
message.setSender(user.getUserID());
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(message);
System.out.println("用户 ["+user.getUserID()+"] 退出");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
StreamUtils .java
package com.leaveriver.utils;
import java.io.*;
public class StreamUtils {
public static byte[] streamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int readLen;
while ((readLen = is.read(bytes)) != -1){
bos.write(bytes, 0, readLen);
}
byte[] array = bos.toByteArray();
bos.close();
return array;
}
public static String streamToString(InputStream is) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
return stringBuilder.toString();
}
}
Utility.java
package com.leaveriver.utils;
import java.util.Scanner;
import java.util.*;
public class Utility {
private static Scanner scanner = new Scanner(System.in);
public static char readMenuSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1, false);
c = str.charAt(0);
if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5') {
System.out.println("选择错误,请重新输入:");
} else break;
}
return c;
}
public static char readChar() {
String str = readKeyBoard(1, false);
return str.charAt(0);
}
public static char readChar(char defaultValue) {
String str = readKeyBoard(1, true);
return str.length() == 0 ? defaultValue : str.charAt(0);
}
public static int readInt() {
int n;
for (; ; ) {
String str = readKeyBoard(2, false);
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.println("选择错误,请重新输入:");
}
}
return n;
}
public static int readInt(int defaultValue) {
int n;
for (; ; ) {
String str = readKeyBoard(2, false);
if (str.equals("")) {
return defaultValue;
}
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.println("选择错误,请重新输入:");
}
}
return n;
}
public static String readString(int limit) {
return readKeyBoard(limit, false);
}
public static String readString(int limit, String defaultValue) {
String str = readKeyBoard(limit, true);
return str.equals("") ? defaultValue : str;
}
public static char readConfirmSelection() {
System.out.println("请输入你的选择(Y/N)");
char c;
for (; ; ) {
String str = readKeyBoard(1, false).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'N') {
break;
} else {
System.out.print("选择错误,请重新输入:");
}
}
return c;
}
private static String readKeyBoard(int limit, boolean blankReturn){
String line="";
while (scanner.hasNextLine()){
line=scanner.nextLine();
if(line.length()==0){
if(blankReturn) return line;
else continue;
}
if(line.length()<1 || line.length()>limit){
System.out.println("输入长度(不大于 "+ limit + ")错误,请重新输入:");
continue;
}
break;
}
return line;
}
}
View.java
package com.leaveriver.view;
import com.leaveriver.service.FileService;
import com.leaveriver.service.MessageService;
import com.leaveriver.service.UserClientService;
import com.leaveriver.utils.Utility;
public class View {
private boolean loop = true;
private String key = "";
private UserClientService userClientService = new UserClientService();
private MessageService messageService = new MessageService();
private FileService fileService = new FileService();
public void mainMenu(){
while(loop) {
System.out.println("=============欢迎登录网络通讯系统=============");
System.out.println("\t\t 1 登录系统");
System.out.println("\t\t 9 退出系统");
System.out.print("请输入你的选择:");
key = Utility.readString(1);
switch (key){
case "1" :
System.out.print("请输入用户号:");
String userID = Utility.readString(20);
System.out.print("请输入密 码:");
String password = Utility.readString(20);
boolean b = userClientService.checkUser(userID, password);
if (b) {
System.out.println("=============欢迎 (用户" + userID +")=============");
while (loop) {
System.out.println("=============网络通讯系统二级菜单 (用户" + userID +")=============");
System.out.println("\t\t 1 显示在线用户列表");
System.out.println("\t\t 2 群发消息");
System.out.println("\t\t 3 私聊消息");
System.out.println("\t\t 4 发送文件");
System.out.println("\t\t 9 退出系统");
System.out.print("请输入你的选择:");
key = Utility.readString(1);
switch (key){
case "1":
userClientService.onlineFriendList();
break;
case "2":
System.out.print("请输入群发消息:");
String chatAll = Utility.readString(50);
messageService.chatAllUsers(userID, chatAll);
break;
case "3":
System.out.print("请输入要私聊的对象用户名:");
String chatToUserId = Utility.readString(20);
System.out.print("私聊内容:");
String chatContent = Utility.readString(100);
messageService.userOneChat(userID, chatContent, chatToUserId);
break;
case "4":
System.out.println("发送文件");
System.out.print("你要发送文件给用户: ");
String fileToUser = Utility.readString(20);
System.out.print("你要发送的文件的完整路径: ");
String fileStartPath = Utility.readString(50);
System.out.print("保存下对方的路径: ");
String fileTarPath = Utility.readString(50);
fileService.sendFile(userID, fileToUser, fileStartPath,fileTarPath);
break;
case "9":
userClientService.systemExit();
loop = false;
break;
}
}
}else {
System.out.println("============登录失败==================");
}
break;
case "9" :
loop = false;
break;
}
}
}
}
QQFrame.java
package com.leaveriver.qqframe;
import com.leaveriver.view.View;
public class QQFrame {
public static void main(String[] args) {
View view = new View();
view.mainMenu();
System.out.println("退出系统。");
}
}
|