2012年8月19日 星期日

gcin在Xming下輸入中文

sudo apt-get install unifont (中文字型)
sudo apt-get install gcin
改變切換熱鍵
echo 2 > ~/.gcin/config/gcin-im-toggle-keys
--------------------------- 
0          Control-Space
1          Shift-Space
2          Alt-Space
3          Windows-Space
--------------------------- 
 
設定遠端輸入  
echo 1 > ~/.gcin/config/gcin-remote-client
--------------------------- 
0         OFF
1         ON
---------------------------
 
主流的 X 輸入法有
1. XIM
2. GTK immodule(給 GTK+ 2 / Gnome 軟體用的,GTK+ 1 不適用)
3. QT immodule(給 QT / KDE 軟體用的)
 
1. XIM 
# 設定 locale
export LC_CTYPE=zh_TW.UTF-8
# 也可以改用 export LANG=zh_TW.UTF-8
# LC_ALL 若無特別需求,不要用。
#設定 XIM name
export XMODIFIERS=@im=gcin
# scim, fcitx, gcin 都會自動判斷 XIM name
# 執行 XIM server
scim -d
# 如果是 gcin 請改用 gcin & 
 
2. GTK immodule
export GTK_IM_MODULE=gcin
 
3. QT immodule
export QT_IM_MODULE=gcin
# 注意,需要安裝 gcin-qt3-immodule 才能使用這個功能

Debian6(lenny) JeOS8.04(hardy) source.list

apt-get下載下來的目錄是/var/cache/apt/archives/

sudo nano /etc/apt/sources.list

 #cdrom
deb cdrom:[Debian GNU/Linux 6.0.5 _Squeeze_ - Official i386 NETINST Binary-1 20120512-20:43]/ squeeze main
------------------------------
# lenny (stable)
deb http://ftp.tw.debian.org/debian stable main contrib non-free
deb-src http://ftp.tw.debian.org/debian stable main contrib non-free

# security
deb http://security.debian.org lenny/updates main contrib non-free
deb-src http://security.debian.org lenny/updates main contrib non-free

# squeeze (testing)
deb http://ftp.tw.debian.org/debian testing main contrib non-free
deb-src http://ftp.tw.debian.org/debian testing main contrib non-free

# sid (unstable)
deb http://ftp.tw.debian.org/debian unstable main contrib non-free
deb-src http://ftp.tw.debian.org/debian unstable main contrib non-free

# experimental
deb http://ftp.tw.debian.org/debian/ ../project/experimental main contrib non-free
deb-src http://ftp.tw.debian.org/debian/ ../project/experimental main contrib non-free
------------------------------
#JeOS 8.04(hardy)
-----------------------------
#deb cdrom:[Ubuntu-JeOS 8.04.3 _Hardy Heron_ - Release i386 (20090714)]/ hardy main restricted

deb http://tw.archive.ubuntu.com/ubuntu/ hardy main restricted
deb-src http://tw.archive.ubuntu.com/ubuntu/ hardy main restricted
deb http://tw.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
deb-src http://tw.archive.ubuntu.com/ubuntu/ hardy-updates main restricted

deb http://tw.archive.ubuntu.com/ubuntu/ hardy universe
deb-src http://tw.archive.ubuntu.com/ubuntu/ hardy universe
deb http://tw.archive.ubuntu.com/ubuntu/ hardy-updates universe
deb-src http://tw.archive.ubuntu.com/ubuntu/ hardy-updates universe

deb http://tw.archive.ubuntu.com/ubuntu/ hardy multiverse
deb-src http://tw.archive.ubuntu.com/ubuntu/ hardy multiverse
deb http://tw.archive.ubuntu.com/ubuntu/ hardy-updates multiverse
deb-src http://tw.archive.ubuntu.com/ubuntu/ hardy-updates multiverse

deb http://security.ubuntu.com/ubuntu hardy-security main restricted
deb-src http://security.ubuntu.com/ubuntu hardy-security main restricted
deb http://security.ubuntu.com/ubuntu hardy-security universe
deb-src http://security.ubuntu.com/ubuntu hardy-security universe
deb http://security.ubuntu.com/ubuntu hardy-security multiverse
deb-src http://security.ubuntu.com/ubuntu hardy-security multiverse

2012年8月18日 星期六

Ubuntu/Debian Server install

設定IP
sudo nano /etc/network/interfaces
-------------------------------
auto eth0
iface eth0 inet dhcp
-------------------------------
或
-------------------------------
auto eth0
iface eth0 inet static
        address 192.168.1.100
        netmask 255.255.255.0
        network 192.168.1.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
-------------------------------

設定DNS
sudo nano /etc/resolv.conf
-------------------------------
# DNS of Google
nameserver  8.8.4.4
nameserver  8.8.8.8

# DNS of HiNet
#nameserver  168.95.1.1
#nameserver  168.95.192.1
# DNS of SeedNet
#nameserver  139.175.55.244
#nameserver  139.175.150.20
-------------------------------
重起網路
sudo /etc/init.d/networking restart

設定X11Forwarding
/etc/ssh/sshd_config
-----------------------
AllowTcpForwarding yes
X11Forwarding yes
---------------------------

sudo nano /etc/default/locale
-----------------------------
LANG="C"
LANGUAGE="C"

#LANG="zh_TW.UTF-8"
#LANGUAGE="zh_TW":zh"

----------------------------- 

Console支援中文
---------------------------
sudo apt-get install install jfbterm unifont
若是grub1
 vim /boot/grub/menu.lst 加 vga=789:
例如: kernel  /vmlinuz-2.6.11-1-686 root=/dev/hda2 ro vga=789
若是grub2
sudo vi /etc/default/grub 
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
修改为
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash VGA=788"
sudo update-grub2

sudo reboot
 之後要用執行jfbterm
---------------------------

檢視磁碟使用量-
df -h

安裝Xorg
-----------------------------------------
sudo apt-get install xorg
-----------------------------------------
安裝 中文字型
-----------------------------------------
sudo apt-get install unifont
或
sudo apt-get install ttf-arphic-uming
-----------------------------------------

xterm顯示中文
-----------------------------------------
xterm -fa -fs 12
或
xterm -fa 'AR PL UMing TW' -fs 12
-----------------------------------------

locale -a 可以查目前系統所支援的 UTF-8 的語言設定
fc-list 可以查詢系統內安裝的字型列表 
 


安裝firefox
-----------------------------------------
Ubuntu是 sudo apt-get install firefox
Debian是 sudo apt-get install iceweasel
安裝flashplugin
sudo apt-get install flashplugin-nonfree
-----------------------------------------

安裝pdfviewer
-----------------------------------------
sudo apt-get insall epdfview
-----------------------------------------

-----------------------------------------
安裝檔案總管nautilus
sudo apt-get install hicolor-icon-theme gnome-icon-theme 
sudo apt-get install nautilus
-----------------------------------------

安裝中文輸入
----------------------------------------
sudo apt-get install gcin
改變切換熱鍵
echo 2 > ~/.gcin/config/gcin-im-toggle-keys

echo  export GTK_IM_MODULE=gcin >> export ~/.bashrc
echo export QT_IM_MODULE=gcin >> export ~/.bashrc
(需要安裝 gcin-qt3-immodule)

重啟gcin:
kill idnumber
gcin &

-----------------------------------------

遠端登入X
----------------------------------------
dpkg-reconfigure x11-common
或
etc/X11/Xwrapper.config設成allowed_users=anybody
----------------------------------------

 重新設置session管理器
update-alternatives --config x-session-manager
 重新設置窗口管理器
update-alternatives --config x-window-manager
 重新設系統默認瀏覽器
update-alternatives --config x-www-browser
 
/etc/gdm/gdm.conf
或 
/usr/share/gdm/defaults.conf
或
/etc/gdm3/daemon.conf 
/etc/gdm/gdm.schemas (ubuntu 10)
/etc/lightdm/lightdm.conf (ubuntu 12)
可看出gdm組態
 
GDM在自動登入時,由 $HOME/.dmrc 決定登入後的 X 使用環境(X session) 
sudo nano .dmrc
------------
[Desktop]
Session=gnome 
------------


Session 名稱,指的是 /usr/share/xsessions 下的 .desktop 
例如 gnome.desktop
-----------
[Desktop Entry]
Name=GNOME
Exec=gnome-session
Type=Application 
-----------
 
 
Name=GNOME
GDM 登入畫面中,顯示給使用者選擇的 X 使用環境名稱。 
 
Exec=gnome-sesion
負責啟動 X 使用環境的執行檔。 
 
Type=Application
規定項目。
當 .dmrc 中指定的 Session 為 default時 看
update-alternatives --display x-session-manager 決定

你可以修改 /etc/default/grub 取消 GDM 登入行為。

改#GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
成GRUB_CMDLINE_LINUX_DEFAULT="text"


 startx 將會先找 $HOME/.xsession (或 $HOME/.Xsession) 再找 x-session-manager 以載入 X 視窗環境,若使用者的家目錄下不存在 .xsession ,startx 就會嘗試執行 /usr/bin/x-session-manager 載入系統預設的 X 視窗環境。
OpenBox 是一種常見的輕量化視窗管理程式(Window Manager)其組態內容請見 /etc/X11/openbox
/etc/X11/openbox 內為 openbox 預設組態文件。而使用者專用組態則位於 $HOME/.config/openbox

autostart.sh
openbox 啟動後,要自動執行的 script 內容。 注意,在此 script 中,想要執行的視窗程式必須要放到背景執行 (最後加上 & 符號),否則會阻礙接下來的內容。

menu.xml
OpenBox 滑鼠右鍵浮動選單的內容。

rc.xml
OpenBox 行為特徵組態內容。包含視窗行為、滑鼠行為、鍵盤行為。



#-----------------------------------
X Window 所需中文
------------------------------
sudo apt-get install language-pack-zh
sudo apt-get install language-support-zh
------------------------------
GNOME 所需中文
------------------------------
$ sudo apt-get install language-pack-gnome-zh

2012年7月29日 星期日

JAVA Httpd Server (with thread)

neotestserver.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;

public class neotestserver{
  public static void main(String args[]) {
    int port;
    ServerSocket server_socket;
    try {
      port = Integer.parseInt(args[0]);
    } catch (Exception e) {
      port = 2222;
    }
    try {
      server_socket = new ServerSocket(port);
      System.out.println("Web伺服器監聽port:"
          + server_socket.getLocalPort());

      // server infinite loop
      while (true) {
        Socket socket = server_socket.accept();
        System.out.println("偵測新的連線在" +socket.getInetAddress() + ":" + socket.getPort());
        try {
          httpRequestHandler request = new httpRequestHandler(socket);
          Thread thread = new Thread(request);
          thread.start();
        } catch (Exception e) {
          System.out.println(e);
        }
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
}

class httpRequestHandler implements Runnable {
  Socket socket;
  InputStream input;
  OutputStream output;
  BufferedReader br;

  public httpRequestHandler(Socket socket) throws Exception {
    this.socket = socket;
    this.input = socket.getInputStream();
    this.output = socket.getOutputStream();
    this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  }
  
  public void run() {
    try {
    	while (true) {
    	      String headerLine = br.readLine();
    	      System.out.println(headerLine);
    	      if (headerLine.equals("\r\n") || headerLine.equals(""))
    	        break;
    	      StringTokenizer s = new StringTokenizer(headerLine);
    	      String temp = s.nextToken();
    	      if (temp.equals("GET")) {
    	    	  String fileName = s.nextToken();  //GET之後是fileName
    	    	  fileName = "." + fileName;		  //fileName前面記得加上"."
    	    	  FileInputStream fis = null;
    	    	  boolean fileExists = true;
    	    	  try {
    	    		  fis = new FileInputStream(fileName);
    	    	  } catch (FileNotFoundException e) {
    	    		  fileExists = false;
    	    	  }
    	    	  String urlstr ="";
    	    	  if (fileExists) {
    	    		  urlstr = "HTTP/1.0 200 OK\r\n" + "Content-type: " + contentType(fileName) + "\r\n" + "Content-Length: " + (new Integer(fis.available())).toString() + "\r\n" + "\r\n";
    	        	  //填上fileName的內容
    	    		  output.write(urlstr.getBytes());
    	    		  byte[] buffer = new byte[1024];
    	    		  int bytes = 0;
    	    		  while ((bytes = fis.read(buffer)) != -1) {
    	    			  output.write(buffer, 0, bytes);
    	    		  }
    	    		  socket.close();
    	    	  } else {
    	    		  urlstr = "HTTP/1.0 404 Not Found\r\n" + "text/html\r\n\r\n" + "<HTML> <HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY>404 Not Found<br>usage:http://yourHostName:port/fileName.html</BODY></HTML>\r\n";
    	    		  output.write(urlstr.getBytes());
    	    		  socket.close();
    	    	  }   
    	      }
    	    }    
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  
  private static String contentType(String fileName) {
    if (fileName.endsWith(".htm") || fileName.endsWith(".html")
        || fileName.endsWith(".txt")) {
      return "text/html";
    } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
      return "image/jpeg";
    } else if (fileName.endsWith(".gif")) {
      return "image/gif";
    } else {
      return "application/octet-stream";
    }
  }
}     

2012年7月28日 星期六

JDBC MySQL

加入mysql-connector-java-5.1.21-bin.jar
package neo.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcMySQL {
 Connection conn;
 String username;
 String password;
 String url;
 String databaseName;
 String port = "3306";
 String sqlstr = "jdbc:mysql://"+url+":"+port+"/"+databaseName+"?useUnicode=true&characterEncoding=UTF-8";
 String userNameString = "name";
 String passwdNameString = "passwd";
 public JdbcMySQL(String url, String databaseName, String username, String password){
  sqlstr = "jdbc:mysql://"+url+":"+port+"/"+databaseName+"?useUnicode=true&characterEncoding=UTF-8";
  //透過java.lang.Class類別的forName()來載入並向DriverManager註冊JDBC驅動程式(驅動程式會自動透過DriverManager.registerDriver()方法註冊), MySQL的驅動程式類別是com.mysql.jdbc.Driver
   try
       {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
       //jdbc:mysql://主機名稱:連接埠/資料庫名稱?參數1=值1&參數2=值2
      conn = java.sql.DriverManager.getConnection(sqlstr,username,password);
   if(!conn.isClosed()) System.out.println("MySQL資料庫連線成功"); 
  } catch (SQLException e) {
   System.out.println("連不上MySQL!!!"); 
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
 public void getConnection(){
   try
       {
         Class.forName("com.mysql.jdbc.Driver").newInstance();
       //jdbc:mysql://主機名稱:連接埠/資料庫名稱?參數1=值1&參數2=值2
      conn = java.sql.DriverManager.getConnection(sqlstr,username,password);
   if(!conn.isClosed()) System.out.println("MySQL資料庫連線成功"); 
  } catch (SQLException e) {
   System.out.println("連不上MySQL!!!"); 
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
 public void close(){
  try {
   conn.close();
  } catch (SQLException e) {
   System.out.println("無法關閉跟MySQL的連線!!!"); 
  }
 }
 public void createTable(){
  String createdbSQL = "CREATE TABLE User (" +
     "    id     INTEGER " +
     "  , name    VARCHAR(20) " +
     "  , passwd  VARCHAR(20))";
  try {
   conn.setAutoCommit(false);
   Statement state = conn.createStatement();
   state.executeUpdate(createdbSQL);
   conn.commit();
  } catch (SQLException e) {
   System.out.println("MySQL新建資料表失敗!!!"); 
   e.printStackTrace();
  } 
 }
 public void insertData(String name, String passwd){
  String insertdbSQL = "insert into User(id,name,passwd) " +
       "select ifNULL(max(id),0)+1,?,? FROM User";
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(insertdbSQL);
   pst.setString(1, name);
   pst.setString(2, passwd);
   pst.executeUpdate();
   conn.commit();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public void updateData(int id,String name, String passwd){
  String insertdbSQL = "update User set name = ? ,passwd = ? where id = ?";
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(insertdbSQL);
   pst.setInt(3, id);
   pst.setString(1, name);
   pst.setString(2, passwd);
   pst.executeUpdate();
   conn.commit();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public void delete(String tableName,String username){
  String sql = "delete from "+tableName+" where "+userNameString+" = ?";
  Statement state;
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(sql);
   pst.setString(1, username);
   pst.execute();
   conn.commit();
   System.out.println("刪除成功!!!");   
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   System.out.println("刪除失敗!!!"); 
   e.printStackTrace();
  }
 }
 public void research(){
  String sql = "select * from User";
  Statement state;
  try {
   conn.setAutoCommit(false);
   state = conn.createStatement();
   ResultSet rs = state.executeQuery(sql);
   conn.commit();
   while (rs.next()) {
    System.out.println(rs.getInt("id"));
    System.out.println(rs.getString("name"));
    System.out.println(rs.getString("passwd"));  
     //System.out.println(rs.toString());
    }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 public boolean validation(String tableName,String username,String passwd){
  String sql = "SELECT "+passwdNameString+" FROM `"+tableName+"` WHERE "+userNameString+"=?";
  try {
   conn.setAutoCommit(false);
   PreparedStatement pst = conn.prepareStatement(sql);
   pst.setString(1, username);
   ResultSet rs = pst.executeQuery();
   conn.commit();
   while (rs.next()) {
    if (rs.getString(passwdNameString).equalsIgnoreCase(passwd)) return true;
   }
   return false;
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return false;
  
 }
}

2012年7月27日 星期五

JAVA multi-client server


MUDApplication.java
package neo.mudserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;


public class MUDApplication {
 public static void main(String[] args) throws InterruptedException, IOException {
  Server myServer = new Server(2222,50,10);
  long timestamp;
  long sleep;
  while(true){
   timestamp = System.currentTimeMillis();
   Client newclient = myServer.acceptNewConnetcion();
   if(newclient != null){
    Date date = new Date();
    System.out.println(date.toString()+"建立了新連線");
    myServer.flush();
   }
   ArrayList<CommandSet> cmds = null;
   cmds = myServer.readMessageFromClient();
   doProcessCommandSet(cmds);
   myServer.flush();
   sleep = 250 - (System.currentTimeMillis() - timestamp);
   if (sleep > 0)
    Thread.sleep(sleep);
  }
 }
 public  static void doProcessCommandSet(ArrayList cmds){
  Iterator<CommandSet> i = cmds.iterator();
  while(i.hasNext()){
   CommandSet command = i.next();
   Client client = command.client;
   String commandmessage = command.commandMessage;
   System.out.println("收到client("+client.ID+")端傳來的訊息:"+commandmessage);
   String colorWhite = (char) 27 + "[1;37m";
   client.write(colorWhite+"Server收到你傳去的message:\""+commandmessage+"\"\r\n");
   if(commandmessage.equalsIgnoreCase("quit")){
    try {
     client.close();
    } catch (IOException e) {
     System.out.println("嘗試關閉client("+client.ID+")端連線失敗");
    }
   }
  }
 }
}


Server.java
package neo.mudserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;

public class Server {
 ServerSocket serversocket;
 ArrayList<Client> clients;
 int port;
 int serverSocketTimeout;
 int clientSocketTimeout;
 public Server(int port, int serverSocketTimeout,int clientSocketTimeout){
  try {
   this.port = port;
   this.serverSocketTimeout = serverSocketTimeout;
   this.clientSocketTimeout = clientSocketTimeout;
   System.out.println("監聽"+port+"埠:");
   serversocket = new ServerSocket(port);
   clients = new ArrayList<Client>();
   serversocket.setSoTimeout(serverSocketTimeout);  //注意要設timeout時間server才不會pending在那裏
  } catch (IOException e) {
   System.out.println(+port+"埠被占用,關閉連線");
  }
 }
 public Client acceptNewConnetcion() throws IOException{
  Client client = null;
  try {
   Socket socket = serversocket.accept();
   client = new Client(this, clients.size(),socket);
   client.socket.setSoTimeout(clientSocketTimeout); //不設timeout的話Server的readMessageFromClient做client.read()就會hold在那裏
   clients.add(client);
   String colorCyan = (char) 27 + "[1;36m";
   client.write(colorCyan+"跟Server建立了連線\r\n");
  } catch (SocketTimeoutException e) {
   //當TimeOut時繼續做acceptNewConnetcion之後的動作所以這裡為空指令
  }
  return client;
 }
 public void flush(){
  Iterator<Client> i = clients.iterator();
  while (i.hasNext()){
   Client currectClient = i.next();
   try {
    currectClient.flush();
   } catch (IOException e) {
    System.out.println("client("+currectClient.ID+")不能被flush");
   }  
  }
 }
 public ArrayList<CommandSet> readMessageFromClient() throws IOException{
  ArrayList<CommandSet> cmds= new ArrayList();
  Iterator i = clients.iterator();
  while(i.hasNext()){
   String inputMessage;
   Client currectClient = i.next();
   try {
    currectClient.read();
   } catch (SocketTimeoutException e) {
    //當TimeOut時視為沒有輸入這裡為空指令
   }
   inputMessage = currectClient.inBuffer;
   if (inputMessage != null) cmds.add(new CommandSet(currectClient, inputMessage));
  }
  return cmds;
  
 }
}

Client.java
package neo.mudserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class Client {
 enum State{promptName,promptNameVerivfy,connected};
 int ID;
 Server server;
 Socket socket;
 StringBuffer outBuffer;
 String inBuffer;
 public Client(Server server, int cliendID, Socket socket) throws SocketException{
  this.ID = cliendID;
  this.server = server;
  this.socket = socket;
  this.outBuffer = new StringBuffer();
  this.inBuffer = null;
 }
 public void write(String message){
  this.outBuffer.append(message);
 }
 public void flush() throws IOException {
  OutputStream outputstream = socket.getOutputStream(); //socket是從server來的所以對server而言是output
  outputstream.write(outBuffer.toString().getBytes());
  outBuffer.setLength(0); //命令輸出了之後要記得清零
 }
 public void read() throws IOException,SocketTimeoutException{
  inBuffer = null;
  BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  inBuffer = br.readLine();
 }
 public void close() throws IOException{
  socket.close();
  server.clients.remove(this);
 }
}

CommandSet.java
package neo.mudserver;

public class CommandSet {
 Client client;
 String commandMessage;
 public CommandSet(Client client, String message){
  this.client = client;
  this.commandMessage = message;
 }
}

2012年7月24日 星期二

Java Applet


用javac -encoding utf-8 neoApplet.java 編譯

neoApplet.java
   import java.awt.*; 
   import java.awt.event.*; 
   import java.applet.Applet; 
   import java.applet.AudioClip;
    
    public class neoApplet extends Applet implements ItemListener,ActionListener,MouseListener,MouseMotionListener{ 
        Button btn;                   //  宣告 Button 型態的變數 btn 
     int image_x=10,image_y=10,dx,dy; 
  Image img; 
  Image imgBackup;      //  宣告 Image 類別型態的變數 imgB 
        Graphics gBackup;      //  宣告 Graphics 類別型態的變數 gB 
     boolean clicked=false;  
  AudioClip midi[]=new AudioClip[2]; //  宣告 AudioClip 介面型態的陣列  
        AudioClip midiplayer;  //  宣告 AudioClip 介面型態的變數 current
        Choice chc=new Choice();   //  建立 Choice 元件    
  public void mouseMoved(MouseEvent e){}   //MouseMotionListener
     public void mouseEntered(MouseEvent e){} //MouseListener
        public void mouseExited(MouseEvent e){}  //MouseListener
        public void mouseReleased(MouseEvent e){}//MouseListener
  public void mousePressed(MouseEvent e) 
  { 
   dx=e.getX()-image_x;  //  取得按下之點與基準點 x 方向之距離
   dy=e.getY()-image_y;  //  取得按下之點與基準點 y 方向之距離 
        } 
  public void mouseDragged(MouseEvent e) 
  { 
     if(dx>0 && dx< Integer.valueOf(getParameter("imageWIDTH")) && dy>0 && dy< Integer.valueOf(getParameter("imageHEIGHT")))  //  如果指標落在圖形上方 
         { 
    image_x=e.getX()-dx;   //  取得拖曳時,基準點的 x 座標 
            image_y=e.getY()-dy;   //  取得拖曳時,基準點的 y 座標 
   paint(getGraphics()); 
            //Graphics g=getGraphics(); 
           // update(g);   //  清空畫面為背景顏色,再呼叫 paint() 
        } 
      } 
  public void mouseClicked(MouseEvent e)
        { 
   }  
      public void init() 
   {  
      midi[0]=getAudioClip(getCodeBase(),"sky.mid"); 
         midi[1]=getAudioClip(getCodeBase(),"panther.mid");   
   midiplayer=midi[0];
   midiplayer.play(); 
   chc.add(" sky "); 
         chc.add(" panther "); 
   add(chc);
   
         btn=new Button(getParameter("buttonCaption"));     //  建立 btn 物件  
         btn.addActionListener(this);  //  以 applet 本身當成 btn 的傾聽者  
   add(btn);  //  將 btn 按鈕加入 applet 視窗裡  
   img=getImage(getCodeBase(),getParameter("imageFileName"));  //  載入圖檔  
   imgBackup=createImage(getWidth(),getHeight()); 
   gBackup=imgBackup.getGraphics();
   
   addMouseListener(this);  //  設定 applet 為自己本身的傾聽者 
   addMouseMotionListener(this);     
         chc.addItemListener(this);   //  把 applet 當成 chc 的傾聽者   
      } 
    public void paint(Graphics g) 
      {
     gBackup.setColor(new Color(255,255,255));      //  設定繪圖顏色為白色  
        gBackup.fillRect(0,0,getWidth(),getHeight()); //  以白色填滿整個畫面  
  gBackup.setColor(Color.blue);     //  設定繪圖顏色為藍色  
        gBackup.fillOval(30,30,50,50);    //  繪出圓形並填滿藍色  
        gBackup.drawImage(img,image_x,image_y,this);  //  將 img 畫上    
  gBackup.setColor(Color.orange);   //  設定繪圖顏色為橘色  
        gBackup.fillOval(60,40,90,90);    //  繪出圓形並填滿橘色 
        g.drawImage(imgBackup,0,0,this);   //  將 imgB 的內容顯示在 applet 上  
  
    } 
      public void actionPerformed(ActionEvent e) 
      { 
   System.out.println("Button was clicked message show in the java console");
         if(btn.getLabel().equals(getParameter("buttonCaption"))) 
   {   
   btn.setLabel("clicked");    //  設定按鈕上方的文字為 Stop 
   }
   else {          
   btn.setLabel(getParameter("buttonCaption"));   //  設定按鈕上方的文字
   }
      } 
    public void itemStateChanged(ItemEvent e) 
       { 
        midiplayer.stop();                      //  停止播放歌曲  
        int index=chc.getSelectedIndex();      //  取得被選取的索引值  
 midiplayer=midi[index];     //  設定播放的歌曲為 midi[index] 
        midiplayer.play();          //  播放歌曲  
       }    
    } 

web.html.
<!-- web.htm --> 
   <HTML> 
   <BODY BGCOLOR = "FFFF00" > 
   <APPLET                      
      CODE    = "neoApplet.class"  
      WIDTH   = "180"           
      HEIGHT  = "180"
      ALT     = " 很抱歉,您的瀏覽器不支援 Java applet" 
      ALIGN   = "MIDDLE"     
      VSPACE  = "20"   
 >
   <PARAM NAME = "buttonCaption" VALUE = "按鈕"> 
   <PARAM NAME = "imageFileName" VALUE = "logo.jpg"> 
   <PARAM NAME = "imageWIDTH" VALUE = "55">
   <PARAM NAME = "imageHEIGHT" VALUE = "55"> 
   </APPLET> 
   </BODY> 
   </HTML> 

要想在前面加package neo.applet; 封裝起來的話
用JAR方式可用 jar cvf neoAppletExample.jar -C ./classes/* .
注意最後有個點,classes下是/classes/neo/applet/neoApplet.class
web_jar.html

   <HTML> 
   <BODY BGCOLOR = "FFFF00" > 
   <APPLET  
         
      CODEBASE   =   "."  
      CODE    = "neo.applet.neoApplet"  
      ARCHIVE = "neoAppletExample.jar"
      WIDTH   = "180"           
      HEIGHT  = "180"
      ALT     = " 很抱歉,您的瀏覽器不支援 Java applet" 
      ALIGN   = "MIDDLE"     
      VSPACE  = "20"   
 >
   <PARAM NAME = "buttonCaption" VALUE = "按鈕"> 
   <PARAM NAME = "imageFileName" VALUE = "logo.jpg"> 
   <PARAM NAME = "imageWIDTH" VALUE = "55">
   <PARAM NAME = "imageHEIGHT" VALUE = "55">
 </APPLET> 
   </BODY> 
   </HTML>