package com.client;
import com.util.JDBCUtility;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.Properties;
import javax.swing.JOptionPane;
public class ChatManager {
private ChatManager() {
}
private static final ChatManager instance = new ChatManager();
public static ChatManager getCM() {
return instance;
}
private MainWIndow window;
public static Socket socket;
private InputStream input;
private OutputStream out;
private BufferedReader reader;
private PrintWriter writer;
public static boolean isConnected = false;
connect t;
public void setWindow(MainWIndow window) {
this.window = window;
}
class connect extends Thread {
public void run() {
try {
String realPath = JDBCUtility.class.getClassLoader().getResource("")
.getFile();
realPath = URLDecoder.decode(realPath, "utf-8");
Properties p = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(
realPath + "/lib/Connection.properties"));
p.load(in);
String ip = p.getProperty("ip");
int prot = Integer.parseInt(p.getProperty("prot"));
socket = new Socket(ip, prot);
showMessage();
} catch (UnknownHostException e) {
System.out.println(4);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "无法连接服务器");
}
}
}
//发送消息
public void sendMessage(String message) {
if (message == null || message.trim().length() == 0) {
return;
}
try {
out = socket.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(out), true);
if (writer != null) {
writer.println(message);
} else {
window.appendText("与服务器断开连接");
}
} catch (IOException e) {
System.out.println(3);
}
}
// 断开与服务端的连接
@SuppressWarnings("deprecation")
public synchronized boolean closeConnection() {
t = new connect();
try {
sendMessage("CLOSE");// 发送断开连接命令给服务器
t.stop();// 停止接受消息线程
// 释放资源
if (reader != null) {
reader.close();
}
if(input!=null){
out.close();
}
if (writer != null) {
writer.close();
}
if(out!=null){
out.close();
}
if (socket != null) {
socket.close();
}
isConnected = false;
return true;
} catch (IOException e1) {
isConnected = true;
return false;
}
}
// 连接服务端
public boolean connectServer() {
try {
t = new connect();
t.start();
isConnected = true;// 已经连接上了
return true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "连接服务器失败!");
isConnected = false;// 未连接上
return false;
}
}
// 接收消息
public void showMessage() {
try {
input = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(input, "utf-8"));
String line = "";
while ((line = reader.readLine()) != null) {
if (line != null) {
window.appendText(line + "\r\n");
}
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "与服务器断开连接");
}
}
}