November 6, 2013

分別用 Java 與 PHP 實現簡單的聊天室 Chat Room

分散式系統第二個作業要寫聊天室,我選擇分別用 JAVA 與 PHP 來實作。


(一) Java 版本

1. Server 端

  • Create an instance of ServerChatroom and bind to a ServerSocket.
  • ServerSocket starts to listen() to incoming Client connection.
  • Once a Client connects to the ServerSocket, a new Socket will be returned.
  • Forward the specific Socket to a WorkerThread which will handle the following communication between the server and the specific client.
  • The id and Socket of clients who are currently connected to the Server are storaged in ArrayList .
  • The WorkerThread uses a blocking reader(act as receive()) in an infinite loop.
  • The WorkerThread will broadcast every message received by the reader to those who are in the ArrayList.
  • Because this is an multi-thread program. We also need to add some Critical Section(synchronized) to keep things thread-safe.

I did not implement the Safe-Exit funciton since the EXIT commmand is not assigned in the assignment. However, the Client can leave the chatroom by Ctrl+C which will evoke a Exception. The Server then will broadcast this event to everyone.

2. Client 端

  • Create a Socket. Connect to the IP:PORT provided by the user.
  • After connected to the Server, create a GetUserInputThread.
  • The MainThread uses a “blocking recevice()” in an infinite loop to listen to incoming message from Server.
  • The GetUserInputThread will listen to stdin(, get uesr input and write to socket.
  • Although MainThread and GetUserInputThread both use blocking receive(), one listening for remote port and one listening for user input, they will not block each other since they are 2 different threads.

3. 執行結果

(二) PHP 版本

1. 提示

最簡單的方法就是用前端 javascript 配合 AJAX 與後端 PHP 溝通,之後看是要 push 或是 pull 都可以。

將前端想像成 Client 端,後端想像成 Server 端就大致能知道怎麼寫了。

事實上 PHP 版本寫法遠比 Java 還簡單,因為聊天室的很多特性對於網頁來說是很 Nature 的。

2. 執行結果