聊天工具代码
//学习的时候做的。 刚刚实现了简单的聊天 还没有做完 不过现在已经没兴趣做了
//聊天工具 - 客户端代码
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class Cl implements Runnable {
Client5 frame = null;
String title = "";
TableDemo frames;
private static String localName = "";
private BufferedReader reader;
private PrintWriter writer;
private Socket socket;
private Hashtable map = new Hashtable();
private List userlist = new ArrayList();
private Client5 checkMap(String read) {
String key = "";
if (read.startsWith("<sendTo>")) {
read = read.substring(read.indexOf("#") + 1, read
.indexOf("</sendTo>"));
key = read.trim();
} else
key = read;
if (map.containsKey(key)) {
frame = (Client5) map.get(key);
return frame;
}
else if (!(map.containsKey(key))) {
frame = new Client5(key);
frame.setVisible(true);
map.put(read.trim(), frame);
}
return frame;
}
public PrintWriter getWriter() {
return writer;
}
public void setWriter(PrintWriter writer) {
this.writer = writer;
}
public String getFrom(String read) {
return read.substring(read.indexOf("<sendTo>") + 8, read.indexOf("#"));
}
public String getTo(String read) {
return read.substring(read.indexOf("#") + 1, read.indexOf("</sendTo>"));
}
public String getMessage(String read) {
return read.substring(read.indexOf("</sendTo>") + 9);
}
public String getTime() {
Date s = new Date();
return " (" + s.getDay() + "月" + s.getDate() + "日" + s.getHours() + ":"
+ s.getMinutes() + ":" + s.getSeconds() + ") ";
}
public void run() {
while (true) {
try {
String read = reader.readLine();
if (read == null || 0 == read.trim().length()) {
return;
}
/** <thisname> 表示 用户名称 */
if (read.startsWith("<thisname>")) {
localName = read.substring(10);
}
/** <userList> 表示 用户列表 */
else if (read.startsWith("<userList>"))
userList(read);
/** <sendTo> 表示 其他用户传来的消息 */
else if (read.startsWith("<sendTo>")) {
String from = getFrom(read);
String to = getTo(read);
if (to.equals(localName)) {
frame = checkMap(read);
frame.setVisible(true);
frame.getMsgView().append(
from + getTime() + ":"n" + getMessage(read)
+ ""n");
}
} else {
System.out.println("收到的消息与规则不匹配" + read);
}
} catch (IOException ie) {
System.out.println("错误= " + ie);
}
}
}
private void connect() {
try {
System.err.println("尝试与服务器连接."n");
socket = new Socket("127.0.0.1", 7778);
System.err.println("聊天准备完毕."n");
reader = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
new Thread(this).start();
} catch (Exception e) {
System.err.println("连接失败..");
}
}
private void userList(String read) {
read = read.substring(10);
String[] reads = read.split("#");
String[][] data = new String[10][2];
for (int i = 0; i < reads.length; i++) {
// if(!localName.equals(reads[i]))
data[i][0] = reads[i];
}
// new 一个列表
String[] columnNames = { "在线用户名单" };
if (userlist.size() != 0) {
for (int i = 0; i < userlist.size(); i++) {
TableDemo s = (TableDemo) userlist.get(i);
s.dispose();
}
}
frames = new TableDemo(columnNames, data);
userlist.add(frames);
// frames.pack();
frames.setVisible(true);
}
public static void main(String[] args) {
Cl client = new Cl();
client.connect();
}
/** 聊天框 面板类---------------------------- */
class Client5 extends Frame {
private TextField nameBox = new TextField(localName);
private TextArea msgView = new TextArea();
private TextField sendBox = new TextField();
public Client5() {
}
public Client5(String title) {
super(title);
msgView.setEditable(true);
add(nameBox, "North");
add(msgView, "Center");
add(sendBox, "South");
msgView.setBounds(500, 10, 400, 500);
sendBox.setBounds(420, 520, 300, 200);
final String titles = title;
sendBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String msg = "<sendTo>" + nameBox.getText() + "#"
+ titles + "</sendTo>" + sendBox.getText();
System.out.println("nameBox = " + nameBox.getText());
System.out.println("titles = " + titles);
writer.println(msg);
System.out.println("msg = " + msg);
sendBox.setText("");
msgView.append(getFrom(msg) + " (" + getTime() + ") "
+ " :"n" + getMessage(msg) + ""n");
} catch (Exception ie) {
System.out.println("======聊天对话框=错误======= " + ie);
}
}
});
pack();
addWindowListener(new WindowAdapter() {// 注册窗口监听器
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public TextArea getMsgView() {
return msgView;
}
public void setMsgView(TextArea msgView) {
this.msgView = msgView;
}
}
/** 在线列表类-------------------------------------- */
class TableDemo extends JFrame {
private boolean DEBUG = true;
public TableDemo(String[] columnName, Object[][] data) { // 实现构造方法
super("RecorderOfWorkers"); // 首先调用父类JFrame的构造方法生成一个窗口
// MyTableModel myModel = new MyTableModel();//myModel存放表格的数据
MyTableModel myModel = new MyTableModel(columnName, data);// myModel存放表格的数据
JTable table = new JTable(myModel);// 表格对象table的数据来源是myModel对象
table.setPreferredScrollableViewportSize(new Dimension(180, 500));// 表格的显示尺寸
// 产生一个带滚动条的面板
JScrollPane scrollPane = new JScrollPane(table);
// 将带滚动条的面板添加入窗口中
this.setBounds(820, 15, 180, 600);
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {// 注册窗口监听器
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// 把要显示在表格中的数据存入字符串数组和Object数组中
class MyTableModel extends AbstractTableModel {
final Object[][] data;
final String[] columnNames;
public MyTableModel(String[] columnName, Object[][] datas) {
columnNames = columnName;
data = datas;
}
// 下述方法是重写AbstractTableModel中的方法,其主要用途是被JTable对象调用,///以便在表格中正确的显示出来。程序员必须根据采用的数据类型加以恰当实现。
// 获得列的数目
public int getColumnCount() {
return columnNames.length;
}
// 获得行的数目
public int getRowCount() {
return data.length;
}
// 获得某列的名字,而目前各列的名字保存在字符串数组columnNames中
public String getColumnName(int col) {
return columnNames[col];
}
// 获得某行某列的数据,而数据保存在对象数组data中
public Object getValueAt(int row, int col) {
return data[row][col];
}
// 判断每个单元格的类型
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
// 将表格声明为可编辑的
public boolean isCellEditable(int row, int col) {
return true;
}
// 改变某个数据的值
public void setValueAt(Object value, int row, int col) {
checkMap((String) data[row][0]);
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
}
}
}
}
//聊天工具 - 服务器代码
import java.net.*;
import java.io.*;
import java.util.*;
public class Server5 {
private ServerSocket server;
String test = "测试数据";
private BManager bMan = new BManager();
private AManager aMan = new AManager();
private Hashtable map = new Hashtable();
public Server5() {
startServer();
}
void startServer() {
try {
server = new ServerSocket(7778);
System.out.println("服务器创建完毕");
} catch (Exception e) {
// TODO: handle exception
}
while (true) {
Socket socket = null;
try {
socket = server.accept();
} catch (Exception e) {
// TODO: handle exception
}
new Chat_Thread(socket).start();
// 当有用户连接时 把其放进map里面 并且用 ip 和 端口号 唯一标识
String flag = "";
try {
flag = socket.getRemoteSocketAddress().toString();
} catch (Exception e) {
System.err.println("数据转换 " + e);
}
bMan.sendToUser("<thisname>"+flag, socket);
map.put(flag, socket);
bMan.add(socket);
aMan.add(flag);
// 用户上线 先把当前所有在线用户信息 以字符串的形式 传递给该用户
bMan.sendToAll(aMan.getFlags());
// 同时 把这个人上线的消息发送给所有人
// 客户端收到这条信息后 更新自己的在线人员列表
// bMan.sendClientInfo();
}
}
class Chat_Thread extends Thread {
Socket socket;
private BufferedReader reader;
private PrintWriter writer;
Chat_Thread(Socket socket) {
this.socket = socket;
}
//服务器 以读取消息为主 根据收到的消息 来判断如何发送消息
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
} catch (Exception e) {
System.err.println("消息读取错误 = " + e);
}
String msg = "";
try {
while ((msg = reader.readLine()) != null) {
System.out.println(msg);
if (msg == null || msg.trim().length() == 0)
continue;
System.out.println(msg);
/**
* 拆开字符串 从中得到 信息传送方向 把信息传递到指定的socket
*
* 如果是以<ALL>开头 就把消息发给全体 如果是以<sendto>开头 ,则取到</sendto>
*/
String sendTo = "";
String sendTo2 = "";
if(msg.startsWith("<sendTo>")){
sendTo = msg.substring(msg.indexOf("#")+1 , msg.indexOf("</sendTo>"));
sendTo2 = msg.substring( msg.indexOf("<sendTo>")+8,msg.indexOf("#") );
}else{
System.out.println("here");
}
bMan.sendToAll(msg);
}
} catch (Exception e) {
System.err.println("############################" + e);
} finally {
try {
aMan.remove(socket.getRemoteSocketAddress().toString());
bMan.remove(socket);
bMan.sendToAll(aMan.getFlags());
if (reader != null)
reader.close();
if (writer != null)
writer.close();
if (socket != null)
socket.close();
reader = null;
writer = null;
socket = null;
System.out.println("客户机离开.");
bMan.sendClientInfo();
} catch (Exception e) {
}
}
}
}
class AManager extends Vector {
/** 通过一个方法 把Vector里面的所有数据 全部以固定格式 放到一个String里面 */
String getFlags() {
String flags = "<userList>";
String flag = "";
for (int i = 0; i < size(); i++) {
flag = (String) elementAt(i);
flags += flag;
if(!( elementAt(i).toString() .equals( (String)this.lastElement()))){
flags+="#";
}
}
return flags;
}
/** 存放在线列表 */
AManager() {
}
void add(String flag) {
super.add(flag);
}
void remove(String flag) {
super.remove(flag);
}
}
class BManager extends Vector {
BManager() {
}
/** 添加删除一个Socket */
void add(Socket sock) {
super.add(sock);
}
void remove(Socket sock) {
super.remove(sock);
}
synchronized void sendToAll(String msg) {
System.out.println("当前用户列表" + msg);
PrintWriter writer = null;
Socket sock;
for (int i = 0; i < size(); i++) {
sock = (Socket) elementAt(i);
try {
writer = new PrintWriter(sock.getOutputStream(), true);
} catch (IOException ie) {
}
if (writer != null)
writer.println(msg);
}
}
synchronized void sendToUser(String msg ,Socket socket) {
PrintWriter writer = null;
try {
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ie) {
}
if (writer != null)
writer.println(msg);
}
/** 向所有人发送当前用户列表 */
synchronized void sendClientInfo() {
String info = "当前聊天人数: " + size();
System.out.println(info);
sendToAll(info);
}
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
public static void main(String[] args) {
Server5 server = new Server5();
System.out.println(server.getTest());
}
}