把 socket 相關程式從 Windows 移植到 Linux,有不少細節需要注意,以下逐項對照。
1)頭文件:Windows 用 winsock.h/winsock2.h;Linux 用 sys/socket.h,錯誤處理則用 errno.h。
2)初始化:Windows 需要呼叫 WSAStartup;Linux 不需要。
3)關閉 socket:Windows 用 closesocket();Linux 用 close()。
4)型別:Windows 用 SOCKET;Linux 用 int。可用巨集統一:
#ifdef WIN32typedef int socklen_t;typedef int ssize_t;#endif#ifdef __LINUX__typedef int SOCKET;typedef unsigned char BYTE;typedef unsigned long DWORD;#define FALSE 0#define SOCKET_ERROR (-1)#endif
5)取得錯誤碼:Windows 用 GetLastError()/WSAGetLastError();Linux 用 errno 變數。
6)設定非阻塞:Windows 用 ioctlsocket();Linux 用 fcntl()。
7)send 函式最後一個參數:Windows 一般設 0;Linux 建議設 MSG_NOSIGNAL,否則送資料出錯後可能導致程式被中斷而退出。
8)毫秒級時間取得:Windows 用 GetTickCount();Linux 用 gettimeofday()。
多執行緒方面:Windows 的 process.h 對應 Linux 的 pthread.h;_beginthread 對應 pthread_create;_endthread 對應 pthread_exit。