發表文章

目前顯示的是 4月, 2012的文章

如何用 Python 建立 HTTP Access Server

只是稍微紀錄一下。 Python 2.x python -m SimpleHTTPServer 9914 Python 3.x python -m http.server 9914

JAVA TCP Echo Server/Client Example Code

基本上我不喜歡 JAVA。倒不是說物件導向(Object-Oriented)的觀念不好,而是我不喜歡 一些簡單的事情也要要用物件導向的觀念來寫 (單單一個 Hello World 也要寫個 Class ...)。當然有人會說 C++ 不也是這樣,以 Hello World 來說,你也要先 include iostream 這個 Class,但起碼它看起來比較像 C,而且開發者不用特地去包一層物件。 抱怨完畢,現在要列在這裡的是 TCP 的 Server 和  Client 的範例程式,範例來源一樣是 http://www.cs.uic.edu/~troy/spring05/cs450/sockets/socket.html 。 在這個範例裡面,要特別注意的是 thread 的用法。在呼叫 start() 的時候,程式會去執行 run() 的函式,下面是 javadoc 的說明。 public void start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method). TCP Server import java . net . * ; import java . io . * ; class TCPEchoServer extends Thread { protected static boolean serverContinue = true ; protected Socket clientSocket ; public static void main ( String [ ] args ) throws IOException

JAVA UDP Echo Server/Client Example Code

說實話,我不會寫 JAVA。我個人的程式語言母語是 C++(感謝廖婉君教授),工作上比較常用的是 C,JAVA 還真的沒碰過。雖然我一直跟別人說,程式語言這東西,只要掌握住一種,要跨入其他語言並不困難,因為已經有最起碼的程式邏輯(迴圈、判斷式等),但其實我也很少去用其他的程式語言。最近因為工作的關係,不得不使用 JAVA,所以就紀錄一些 JAVA 的範例程式在這裡,以便未來使用。 在這裡要紀錄的是 UDP 的 Echo Server 和 Client 的程式。資料來源為  http://www.cs.uic.edu/~troy/spring05/cs450/sockets/socket.html 。 UDP Echo Server import java . io . * ; import java . net . * ; class UDPServer { public static void main ( String args [ ] ) throws Exception { int serverPort = 9876 ; try { if ( args . length > 0 ) { serverPort = new Integer ( args [ 0 ] ) . intValue ( ) ; } DatagramSocket serverSocket = new DatagramSocket ( serverPort ) ; byte [ ] receiveData = new byte [ 1024 ] ; byte [ ] sendData = new byte [ 1024 ] ; while ( true ) { receiveData

Linux TCP Echo Server/Client Example Code

本篇主要在紀錄 TCP/IP 的程式範例。為什麼要紀錄呢?因為年紀大了,很多程式都想撿現成的來改就好了。要用的時候還要找就太麻煩了,所以乾脆找一個自己想要的版本紀錄起來,以後要用就有了。這次的紀錄重點,包含了: Linux Socket Programming. Select Usage. 範例程式主要來自下面這本書: TCP/IP Sockets in C: Practical Guide for Programmers, Second Edition (ISBN: 978-0-12-374540-8) by Kenneth L. Calvert and Michael J. Donahoo 其實我根本沒買書啦,反正網路上有 範例程式 可以下載,我就直接拿來改囉。 下面就是改寫後的程式碼。改寫的部份主要是風格的問題,以及不想讓 client 傳完一個句子就關閉 socket。 Server: # include < stdio.h > // for printf() and fprintf() # include < sys/socket.h > // for socket(), bind(), and connect() # include < arpa/inet.h > // for sockaddr_in and inet_ntoa() # include < stdlib.h > // for atoi() and exit() # include < string.h > // for memset() # include < unistd.h > // for close() # include < sys/time.h > // for struct timeval {} # include < fcntl.h > // for fcntl() # define MAXPENDING 5 // Maximum outstanding conn