Re: [課業] ftp兩三事

看板NTUE-CS100作者 (mat)時間16年前 (2009/06/04 02:57), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串5/6 (看更多)
前一篇裡我們用了兩個自定的函數 writeString(): 將字串寫進socket readString() : 則會從socket讀出字串 用法如下 writeString( socket, 字串 ); readString ( socket, 字串 ); 這是我自己寫的函數,為什麼要寫這兩個函數呢? 課本內建的函數readn()和writen() readn()會從socket讀n bytes,writen()則是寫n bytes 我舉個例子,假設今天server要告訴client一句話 Server這樣寫 =============== char talk[] = "hi girl~"; //這行字串8 bytes write(connfd, talk, strlen(talk) ); ... Client準備接收這一句話 =================== char talk[512]; readn(sockfd, recv_str, ???? ); //要收幾個bytes? 不知道耶┐(─_─)┌ //天知道server送了幾個bytes過來.... 所以最好的方法就是送資料之前先告知對方資料長度 1.我要送25個bytes囉 2.接著才把25個bytes內容寫過去 對方就可以 1.收到數字25,準備好接收內容 2.呼叫readn(sockfd, buffer, 25) 準確接收,一字不差! 以下是實做內容 void writeString(int sockfd, char *buffer){ int length = strlen(buffer); writeInt(sockfd, length); //先把字串長度寫過去 writen(sockfd, buffer, length); //再來才送字串內容 } void readString(int sockfd, char *buffer ){ int len = readInt(sockfd); //先取得字串長度len readn(sockfd, buffer, len); //恰好收取len個bytes。 buffer[len] = 0; //字串結尾 } 上面又呼叫了兩個自訂函數writeInt() 跟 readInt() 有興趣的人就自己研讀吧 //將整數number寫進socket void writeInt(int sockfd, int number){ char str_num[12+1]; sprintf(str_num, "%12d", number); writen( sockfd, str_num, 12); } //從socket讀取一個整數 int readInt( int sockfd ){ char str_num[12+1]; readn(sockfd, str_num, 12); str_num[12] = 0; int number = atoi(str_num); return number; } -- -- P_Mat <無名個人版> bbs.wretch.cc -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.68.15.209 ※ 編輯: chchwy 來自: 140.115.50.29 (06/15 14:14)
文章代碼(AID): #1A9iUDjU (NTUE-CS100)
文章代碼(AID): #1A9iUDjU (NTUE-CS100)