package javac;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Server extends JFrame {
private ObjectOutputStream out;
private ObjectInputStream in;
private ServerSocket ss;
private Socket socket;
private JTextField tf_message;
private Server frame;
private JButton btn_send;
private JTextArea ta_show;
private JScrollPane scrollPane1;
public Server()
{
super ("Server-服务器端程序");
Container container = getContentPane();
container.setLayout( new FlowLayout() );
tf_message=new JTextField( 10 );
container.add( tf_message );
btn_send = new JButton( "发送" );
btn_send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btn_sendActionPerformed(e);
}
private void btn_sendActionPerformed(ActionEvent e) {
// TODO 自动生成方法存根
}
});
container.add( btn_send );
setSize( 275, 100 );
setVisible( true );
Box box = Box.createHorizontalBox();
ta_show = new JTextArea( 5, 12 );
ta_show.setEditable(false );
box.add( new JScrollPane(ta_show) );
container.add( box );
setSize( 500, 400 );
setVisible( true );
frame = new Server();
frame.setVisible(true);
try {
ss = new ServerSocket(8888);
frame.show("等待连接,请稍候……");
socket = ss.accept();
frame.show(" 已与客户端建立连接!");
out=new ObjectOutputStream(socket.getOutputStream());
frame.setOut(out);
out.flush();
in = new ObjectInputStream(socket.getInputStream());
String message = "";
while (true) {
try {
message = (String) in.readObject();
System.out.println(message);
if (message.equals(Constant.CONNECT_QUIT)) {
frame.setOut(null);
break;
}
frame.show("客户端>> " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
frame.show("客户端" + socket.getInetAddress().getHostName()+ "中断了连接!");
out.close();
in.close();
socket.close();
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Server application = new Server();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void setOut(ObjectOutputStream out) {
this.out = out;
}
public void show(String mess) {
ta_show.append(mess + "\n");
ta_show.setCaretPosition(ta_show.getText().length());
}