2012年6月6日 星期三

Intermediate Java(45) - How to Send Messages


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

public class Server extends JFrame {
private JTextField userText;
private JTextArea chatwindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;

//constructor
public Server(){
super("My Awesome Instant Messenger");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText,BorderLayout.NORTH);
chatwindow = new JTextArea();
add(new JScrollPane(chatwindow));
setSize(400,200);
setVisible(true);
}
//設置和運行server
public void startRunning(){
try{
server = new ServerSocket(6789,10); → 服務器端口(port)和多少人可以等待
while(true){
try{
//連接並有談話
waitForConnection(); → 等待有人連接服務器的函數
setupStreams(); → 設置Stream可以接收和發送的函數
whileChatting(); → 聊天時做什麼的函數
}catch(EOFException eofException){ → 當連接結束例外處理
showMessage("\n Server ended the connection");
}finally{
closeCrap();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//等待連接,然後顯示連接信息
private void waitForConnection() throws IOException{
showMessage("Waiting for someone connect....\n");
connection = server.accept(); → 當有人嘗試連接server,接受連接
showMessage("Now connected to "+connection.getInetAddress().getHostName());
}

//獲得Stream發送和接收數據
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush(); → 當完成發送的動作,然後刷新
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Stream are now setup! \n");
}

//當聊天對話
private void whileChatting() throws IOException{
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do{
//有一個對話
try{
message = (String)input.readObject(); → 服務器收到什麼改為String
showMessage("\n"+ message); → 隔行顯示
}catch(ClassNotFoundException classNotFoundException){ → 如果用戶發送無法識別
showMessage("\n Oh my God! what you sent");
}
}while(!message.equals("CLIENT – END")); → 當客戶端END,不連接Server
}

//完成聊天後關閉Streamconnection
private void closeCrap(){
showMessage("\n Closing connections... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOExcetion ioException){
ioException.printStackTrace();
}
}

//發送消息到客戶端
private void sendMessage(String message){
try{
output.writeObject("SERVER - "+message);這個對象寫入到input
output.flush(); 刷新和清除內存
showMessage("\nSERVER - " + message);
}catch(IOException ioException){ 如果發送消息有錯誤
chatwindow.append("\n ERROR:I CAN'T SEND THAT MESSAGE"); → chatwindow顯示消息
}
}
}

沒有留言:

張貼留言