packagecom.wjy.server;importjava.awt.BorderLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.ServerSocket;importjava.net.Socket;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JTextArea;importjavax.swing.JTextField;/*** caution:boot the server first.
*@authorJiyuan Wang
**/
public class TalkServer extends JFrame implementsActionListener{private static JButton send=null;private static JTextField inputText=null;private static JTextArea showText=null;private static ServerSocket serverSocket=null;private static Socket socket=null;private static DataInputStream dataInputStream=null;private static DataOutputStream dataOutputStream=null;publicTalkServer(){
send=new JButton("Send");
send.addActionListener(this);
send.setEnabled(true);
inputText=newJTextField();
showText=newJTextArea();
add(send,BorderLayout.NORTH);
add(inputText, BorderLayout.SOUTH);
add(showText, BorderLayout.CENTER);
setTitle("Server");
setBounds(1000,0,400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}public static voidmain(String[] args)
{newTalkServer();try{
serverSocket=new ServerSocket(4170);
socket=serverSocket.accept();
showText.append("Connect successd.\n");
dataInputStream=newDataInputStream(socket.getInputStream());
dataOutputStream=newDataOutputStream(socket.getOutputStream());while (true) {
showText.append("Client said: "+dataInputStream.readUTF()+"\n");
}
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
@Overridepublic voidactionPerformed(ActionEvent e) {//TODO Auto-generated method stub
try{
dataOutputStream.writeUTF(inputText.getText());
dataOutputStream.flush();//本人一直把这个程序调试不通,最后发现没加这句话导致服务端显示不了客户端的输入。
showText.append("I said: "+inputText.getText()+"\n");
}catch(IOException e1) {//TODO Auto-generated catch block
e1.printStackTrace();
}
}
}