package
day22.chatroom;
import
java.io.BufferedReader;
import
java.io.File;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;
import
java.io.PrintWriter;
import
java.net.ServerSocket;
import
java.net.Socket;
import
java.text.SimpleDateFormat;
import
java.util.Date;
import
java.util.HashSet;
/**
* 聊天室服务端
*
* Create 2009-2-25
*/
public
class
ChatRoomServer {
private
ServerSocket ss;
// 集合保存 所有连接的用户
private
HashSet<Socket> allSockets;
private
String str =
null
;
public
ChatRoomServer() {
try
{
// 端口号8888
ss =
new
ServerSocket(
8888
);
}
catch
(IOException e) {
System.out.println(e.getMessage() +
"1"
);
}
// 将连接的用户加入集合
allSockets =
new
HashSet<Socket>();
}
/*
* 启动服务
*/
public void startServer() throws IOException {
System.out.println("聊天室服务器启动...");
while (true) {
Socket s = ss.accept();
allSockets.add(s);
new ServerThread(s).start();
}
}
class ServerThread extends Thread {
private Socket s;
private BufferedReader br = null;
private PrintWriter pw1 = null;
public ServerThread(Socket s) {
this.s = s;
}
public void run() {
try {
while (true) {
// 输入字符流
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
str = br.readLine();
if (str.indexOf("%EXIT%") == 0) {
allSockets.remove(s);
sendMesg(str.split(":")[1] + "离开了。");
break;
} else {
sendMesg(str);
}
}
} catch (IOException e) {
System.out.println(e.getMessage() + "2");
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void sendMesg(String str) throws IOException {
Date date = new Date();
String st = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(date);
writeFile(str + "t[" + st + "]");
// 遍历allSockets
for (Socket so : allSockets) {
// 输出字符流
pw1 = new PrintWriter(new OutputStreamWriter(so
.getOutputStream()));
pw1.println(str + "t[" + st + "]");
// 强制清空缓冲流
pw1.flush();
}
}
}
/*
* 将聊天记录写入文件
*/
public void writeFile(String str) {
PrintWriter pw = null;
try {
File f1 = new File("D:\temp\mytt\log.txt");
if (!f1.exists()) {
f1.mkdirs();
}
File f2 = new File(f1, "MyTT_history");
if (!f2.exists()) {
try {
f2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
pw = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(f2)));
pw.println(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
public static void main(String... strings) {
try {
new ChatRoomServer().startServer();
} catch (IOException e) {
System.out.println(e.getMessage() + "3");
}
}
}
======================================================================================
package day22.chatroom;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 瀹㈡埛绔�Create 2009-2-25
*/
public class ChatRoomClient {
private Socket s;
private PrintWriter pw = null;
private BufferedReader br = null;
public ChatRoomClient(String host, int port) throws UnknownHostException,
IOException {
s = new Socket(host, port);
}
public void close() {
if(s!=null){
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(pw!=null){
pw.close();
}
if(br!=null){
try {
br.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
public void sendMessage(String str) {
try {
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pw.println(str);
// 鍒锋柊
pw.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public String reciveMessage() {
try {
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
return br.readLine();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
}
==========================================================================================
package day22.chatroom;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
/**
* 客户界面端
*
* Create 2009-2-25
*/
public class ClientFrame extends JFrame {
/**
*
*/
private
static
final
long
serialVersionUID = 1L;
private
Container content;
private
JTextField field;
private
JTextArea area;
private
JButton b;
private
JLabel label;
private
ChatRoomClient client;
private
String userName;
public
ClientFrame() {
String host1 =
null
;
do
{
String host = JOptionPane.showInputDialog(
this
,
"请输入服务器地址"
);
if
(host ==
null
) {
JOptionPane.showMessageDialog(
this
,
"服务器地址为空"
,
"ERROR"
,
JOptionPane.ERROR_MESSAGE);
System.exit(
0
);
}
else
{
host1 = host;
}
try
{
client =
new
ChatRoomClient(host1,
8888
);
}
catch
(IOException e) {
JOptionPane.showMessageDialog(
this
,
"无法建立连接"
,
"ERROR"
,
JOptionPane.ERROR_MESSAGE);
}
}
while
(client ==
null
);
userName = JOptionPane.showInputDialog(
"请输入使用<MyTT>呢称!"
);
if
(userName==
null
||userName.trim().length()==
0
){
//用户名不写默认为mkk加一个随机数
userName=
"MyTT"
+(
int
)(Math.random()*
10
);
}
this
.setTitle(
"MyTT 1.0"
);
content =
this
.getContentPane();
// 文本框加入中央
area =
new
JTextArea(
10
,
10
);
// 设置文本框的边界
area.setBorder(BorderFactory.createRaisedBevelBorder());
area.setFont(
new
Font(
"宋体"
, Font.PLAIN,
15
));
area.setBackground(
new
Color(
254
,
255
,
240
));
area.setForeground(Color.BLUE);
area.setEditable(
false
);
JScrollPane jsc =
new
JScrollPane(area);
jsc.setBackground(Color.LIGHT_GRAY);
jsc.setBorder(BorderFactory.createEmptyBorder(
5
,
5
,
5
,
5
));
content.add(jsc, BorderLayout.CENTER);
// 南边界面
JPanel pan =
new
JPanel();
pan.setBackground(
new
Color(
240
,
240
,
240
));
pan.setLayout(
new
FlowLayout(FlowLayout.LEADING));
label =
new
JLabel(
"monkeyk"
);
if
(userName.trim().length() <
1
) {
label.setText(
"monkeyk"
);
}
else
{
label.setText(userName);
}
label.setForeground(Color.BLACK);
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED,
Color.white, Color.LIGHT_GRAY));
pan.add(label);
// 文本框
field =
new
JTextField(
20
);
field.setBorder(BorderFactory.createLoweredBevelBorder());
pan.add(
new
JScrollPane(field));
b =
new
JButton(
" 发送 "
);
b.setBorder(BorderFactory.createRaisedBevelBorder());
b.setBackground(Color.LIGHT_GRAY);
pan.add(b);
content.add(pan, BorderLayout.SOUTH);
addEventHandler();
}
public
void
addEventHandler() {
b.addActionListener(
new
ActionListener() {
@Override
public
void
actionPerformed(ActionEvent arg0) {
if
(!field.getText().equals(
""
)) {
client.sendMessage(userName +
">"
+ field.getText());
field.setText(
""
);
}
}
});
field.addActionListener(
new
ActionListener() {
@Override
public
void
actionPerformed(ActionEvent arg0) {
if
(!field.getText().equals(
""
)) {
client.sendMessage(userName +
">"
+ field.getText());
field.setText(
""
);
}
}
});
this
.addWindowListener(
new
WindowAdapter() {
@Override
public
void
windowClosing(WindowEvent arg0) {
int
op = JOptionPane.showConfirmDialog(ClientFrame.
this
,
"你确定要退出吗?"
,
"退出聊天室"
, JOptionPane.OK_CANCEL_OPTION);
if
(op == JOptionPane.OK_OPTION) {
client.sendMessage(
"%EXIT%:"
+ userName);
try
{
Thread.sleep(
300
);
}
catch
(InterruptedException e) {
System.out.println(e.getMessage());
}
client.close();
System.exit(
0
);
}
}
});
}
public
void
showMe() {
new
ReadMessage().start();
this
.setBounds(
300
,
200
,
350
,
220
);
this
.setVisible(
true
);
this
.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private
class
ReadMessage
extends
Thread {
public
void
run() {
while
(
true
) {
String str = client.reciveMessage();
area.append(str +
"n"
);
}
}
}
public
static
void
main(String... strings) {
new
ClientFrame().showMe();
}
}
|