import java.io.*;
import java.net.*;
import java.util.Date;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ServerFrame extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel l1=new JLabel("聊天:"),
l2=new JLabel("");
JTextArea chatLog=new JTextArea(15,50),
reslutlog=new JTextArea(5,50),
note=new JTextArea(5,50);
JButton sendBut=new JButton("发送"),
getBut=new JButton("查看聊天记录");
ServerSocket server=null;
Socket socket=null;
BufferedReader is;//读缓冲区,用于获取另一端发来的信息
PrintWriter os;//输出流,完成向另一端发送信息
ServerFrame(){
super("服务器端程序");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(l1);
this.add(new JScrollPane(chatLog));
this.add(new JScrollPane(reslutlog));
this.add(new JScrollPane(note));
this.add(sendBut); sendBut.addActionListener(this);
this.add(getBut); getBut.addActionListener(this);
this.addWindowListener(new WindowAdapter(){//在关闭窗体的时候,关闭输入输出流和套接字
public void windowClosing(WindowEvent e) {
try {
is.close();
socket.close();
server.close();
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
}
}
});
this.setBounds(100,100,580,560);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(3);
try {
server=new ServerSocket(4700);//创建服务器
socket=server.accept();//等待客户端接入
os=new PrintWriter(socket.getOutputStream());
is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//*******************************************************************************
String s=is.readLine();
if((s!=null)&&(!s.equals("")))
chatLog.append("客户说:"+s.toString()+"\n");
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==getBut){
if(chatLog.getText().trim().length()==0)
{
return;
}
else {
try {
String L=is.readLine();
if((L!=null)&&(!L.equals("")))
reslutlog.append("客户说:"+L.toString()+"\n");
} catch (IOException e1) {
JOptionPane.showMessageDialog(null,"读取消息失败!","提示",JOptionPane.ERROR_MESSAGE);
}
}
}
else if(e.getSource()==sendBut){
os.println(note.getText().trim()+" "+new Date().toLocaleString());
os.flush();
chatLog.append("我说:"+note.getText().trim()+" "+new Date().toLocaleString()+"\n");
}
}
public static void main(String args[]){
new ServerFrame();
}
}