2011年5月25日 星期三

用Python實作簡單的網路通訊

這次就來講解一下用 Python 來實作 TCP/IP 的通訊
程式碼不長, 說明全寫在註解中

Server Side Source Code
# -*- coding: utf-8 -*-
import socket
import threading

HOST = ''
# 設定 Server Port
PORT = 50008
# 紀錄 Client 傳送資料的 Thread
threads = []
# 紀錄 Client 連線資訊
socketConn = {}
global s

# Receive Data From Client 
def thread_socket_conn_recv(connObj, addrObj):
    while True:
        # 等待接收 Client 傳送的資料
        data = connObj.recv(1024)
        if not data: break
        msg = addrObj[0] + ':' + data
        print msg
        
        # Send To All Client This Message
        for key in socketConn:
                    socketConn[key].send(msg)

# Receive Client Connection
def thread_socket_conn_accept(socketObj):
    while True:
        # 等待接收 Client 連線需求
        conn, addr = socketObj.accept()
        print "Connected ", addr

        # 透過 Thread 收接 Client 傳送資料
        t = threading.Thread(target=thread_socket_conn_recv, args=(conn, addr))
        t.start()
        threads.append (t)      
        socketConn[addr] = conn

       # Send To All Client This New Client Connect Alert
        for key in socketConn:
                    msg = 'Welcome ' + addr[0]
                    socketConn[key].send(msg)
                    
def main():
    global s
    # socket.socket 有二個參數
    # 第一個參數定義 socket 是屬於 Internet 還是 local
    #   分別為 socket.AF_INET(預設), socket.AF_INET6 與 socket.AF_UNIX(本機)
    # 第二個參數定義資料流通常只用 socket.SOCK_STREAM 或 socket.SOCK_DGRAM
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # 挷定 address 跟 port
    s.bind((HOST, PORT))
    
    # 設定 socket 最大連線佇列(Queue)數, 數值上限是與系統主機有關, 通常為 5
    s.listen(0)
    
    # 透過 Thread 收接 Client 連線需求
    mainT = threading.Thread (target=thread_socket_conn_accept, args=(s,))
    mainT.start()
    
if __name__ == '__main__':
    main()

Client Side Source Code
# -*- coding: utf-8 -*-
import socket
import threading

# 設定 Server IP
HOST = '127.0.0.1'
# 設定 Server Port
PORT = 50008
global s

def thread_socket_conn_recv(connObj):
 while True:
                # 等待接收 Server 傳送的資料
  data = connObj.recv(1024)
  if not data: break
  print data

def main():
    global s
    # socket.socket 有二個參數
    # 第一個參數定義 socket 是屬於 Internet 還是 local
    #   分別為 socket.AF_INET(預設), socket.AF_INET6 與 socket.AF_UNIX(本機)
    # 第二個參數定義資料流通常只用 socket.SOCK_STREAM 或 socket.SOCK_DGRAM
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 向 Server 請求連線
    s.connect((HOST, PORT))

    # 透過 Thread 收接 Server 傳送資料
    recvT = threading.Thread (target=thread_socket_conn_recv, args=(s,))
    recvT.start()

if __name__ == '__main__':
    main()


可以直接執行, 先執行 Server, 再執行 Client

2011年5月23日 星期一

C 語言隨機產生浮點數值

C 語言的 Rand() 所產生的是整數值, 想產生浮點數就得自己寫了

隨著 compiler 的不同而所產生出來的最大值(RAND_MAX)也有所變化

通常常見的值為
215-1=32767

而另一個常見的值為
231-1=2147483647

寫法可參考以下 Source Code
/************************************************************************/
/* 隨機產生亂數 (Double)                                                */
/************************************************************************/
double randDouble(double lower, double upper)
{
 int range;           /* 想要產生亂數的區間值 */
 double randomValue;  /* 記錄隨機產生的數值 */

 range = upper - lower;
 
 randomValue = (double) rand();       /* 取得隨機值 */
 randomValue = randomValue / RAND_MAX;   /* 轉換成介於 0 與 1 之間 */
 randomValue = randomValue * range;      /* 調整至要產生的區間值 */
 randomValue = randomValue + lower;      /* 調整至正確對應的值 */

 return randomValue;
}


參考網站
casting Rand () to generate double, float

C# 讀取 CSV 檔

直接將 Source Code 貼出來給你們參考

做法跟使用 ADO 方式一樣

說明請參考 Source Code 的註解就會明白了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace LoadCSVDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            OleDbConnection conn = null;
            OleDbCommand comm = null;
            OleDbDataReader dr = null;
            string sql = "select * from [TestData.csv]"; // TestData.csv <-- 想要載入的 CSV 檔檔名
            // Data Source 的參數表示想載入的 CSV 檔的路徑位置
            // Extended Properties 中
            // --> Text 表示要載入的檔案屬性屬於文字檔
            // --> HDR = NO 表示第一行的資料非標頭欄位
            // --> HDR = YES 表示第一行的資料為標頭欄位
            string connectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\;Extended Properties='Text;HDR=NO'";

            try
            {
                conn = new OleDbConnection(connectString);
                conn.Open();

                comm = conn.CreateCommand();
                comm.CommandText = sql;

                dr = comm.ExecuteReader();
                while (dr.Read())
                {

                    Console.WriteLine("{0}\t\t{1}\t\t{2}", dr[0], dr[1], dr[0]);

                }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                    conn.Close();
            }

            Console.Read();
        }
    }
}




不過當你的系統是 64 位元時, 會發生以下問題








因為Jet不支援 64 位元, 所以必需編譯成 32 位元
請修改建置-->平台目標-->選擇 x86













再執行程式

2011年5月18日 星期三

C# 產生不重覆的隨機數值

要產生隨機而不重覆的數值可以參考以下語法

...
Random Counter = new Random(Guid.NewGuid().GetHashCode());
...

參考網站 : 不同的Random物件給予不同的亂數種子