2012年6月7日 星期四

Intermediate Java(57) - showMessage and ableToType


import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JFrame{
private JTextField userText;
private JTextArea chatwindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;

//constructor
public Client(String host){
super("Client mofo!");
serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendData(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatwindow = new JTextArea();
add(new JScrollPane(chatwindow), BorderLayout.CENTER);
setSize(400,200);
setVisible(true);
}

//連接到服務器(Server)
public void startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeCrap();
}
}

//connectToServer函數
private void connectToServer() throws IOException{
showMessage("Attempting connection...\n");
connection = new Socket(InetAddress.getByName(serverIP),6789);
showMessage("Connected to:" + connection.getInetAddress().getHostName());
}

//設置發送和接收消息的Stream
private void setupStreams() throws IOException{
output =new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nyour streams are now good to go");
}
//當與服務器聊天
private void whilechatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classNotfoundException){
showMessage("\n I don't know that object type");
}
}while(!message.equals("SERVER - END"));
}
//關閉Streamsconnection
private void closeCrap(){
showMessage("\n closing crap down...");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}

//發送消息到服務器
private void sendData(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " +message);
}catch(IOException ioException){
chatwindow.append("\n Can not send the message!");
}
}

//更新chatwindow
private void showMessage(final String m){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatwindow.append(m);
}
}
);
}
//給用戶的權限,在文本框中鍵入
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}

在這個class中的所有的意義,比如Server一樣

沒有留言:

張貼留言