package cn.verp.server; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Date; import javax.swing.JOptionPane; import cn.verp.model.DataPack; import cn.verp.swing.LoginFm; import cn.verp.swing.MainFm; public class ClientConnectionService extends Thread { private Socket socket; private LoginFm loginSw; private MainFm mainSw; private ObjectInputStream ois; private ObjectOutputStream oos; public ClientConnectionService(LoginFm loginSw){ this.loginSw = loginSw; } public DataPack receive() throws Exception{ if (checkConnectionIsAction()) { Object obj = ois.readObject(); if (obj != null) { DataPack dp = (DataPack) obj; return dp; } } return null; } private void sendMessage(DataPack dp) throws IOException{ dp.put(DataPack.KEY_CLIENTUPTIME, new Date()); this.oos.writeObject(dp); this.oos.flush(); this.oos.reset(); } // 连接服务器,由构造方法调用 private void connect2Server(String hostAddress, int port) throws IOException { this.socket = new Socket(hostAddress, port); } // 用户登录,向服务器端传送用户名 // 返回true表示登录成功 // 返回false表示登录失败 public String login(DataPack dp) { String loginResult = null; try { // 连接服务器 this.connect2Server(dp.getStr(DataPack.KEY_CLIENTIP), dp.getInt(DataPack.KEY_CLIENTPORT)); this.oos = new ObjectOutputStream( this.socket.getOutputStream() ); // 向服务器端发送用户的登录信息(其中包含了用户名) sendMessage(dp); this.ois = new ObjectInputStream( this.socket.getInputStream() ); // 读取服务器端的响应结果,判断用户是否登录成功 DataPack rdp = receive(); // 登录成功 if ("success".equals(rdp.getMsg())) { // 打开聊天室主窗口 this.mainSw = new MainFm("用户-"+dp.get(DataPack.KEY_USERNAME),this); this.loginSw.setVisible(false); this.loginSw.dispose(); loginResult = "200"; }else if("failure".equals(rdp.getMsg())){ loginResult = "用户名已登录"; } } catch (Exception ex) { loginResult = ex.getMessage(); if ("Connection refused: connect".equals(ex.getMessage())) { loginResult = "远程服务连接不上!"; } } return loginResult; } public void sendMessage(String message, int type) throws IOException { if (checkConnectionIsAction()) { DataPack dp = new DataPack(message, type); dp.put(DataPack.KEY_USERNAME, this.loginSw.getUsername().getText()); sendMessage(dp); } } @Override public void run() { try { while (checkConnectionIsAction()) { DataPack rdp = receive(); if (rdp.getMsg().equals("serverClosing")) { sendMessage("serverClosing", 4); close(); }else if (rdp.getType() == 2) { this.mainSw.getJTextArea1().append(rdp.getMsg()); } } } catch (Exception ex) { //ex.printStackTrace(); JOptionPane.showMessageDialog( this.mainSw, "服务器端出现异常,请退出程序重新登录!", "信息", JOptionPane.INFORMATION_MESSAGE); } } private void close() throws IOException { if (checkConnectionIsAction()) { this.ois.close(); this.oos.close(); this.socket.close(); } } public boolean checkConnectionIsAction(){ if (socket.isClosed()) { JOptionPane.showMessageDialog( this.mainSw, "连接已断开,请退出程序重新登录!", "信息", JOptionPane.INFORMATION_MESSAGE); return false; } return true; } }