[問題] socket程式 自己輸入IP後client卡住

看板C_and_CPP (C/C++)作者時間9年前 (2016/11/19 12:43), 9年前編輯推噓3(304)
留言7則, 4人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) VS 2015 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) C++ WIN32主控台應用程式 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) client: #include <iostream> #include <string> using namespace std; #include "winsock2.h" #pragma comment(lib, "ws2_32.lib") server: #include <iostream> using namespace std; #include "winsock2.h" #pragma comment(lib, "ws2_32.lib") 問題(Question): 我寫了一對socket的小程式 client利用server的IP跟port來通訊 client在連線後輸入任意字元 server收到之後回傳給client client顯示server的回傳 原程式運作OK 現client增新宣告及新程式段 char IP_char[17]; cout << "please key in IP:"; cin >> IP_char; cout << "\n"; //換行 原serverIP宣告 servAddr.sin_addr.s_addr = inet_addr("36.227.47.199"); 改為 servAddr.sin_addr.s_addr = inet_addr(IP_char); 另持續給使用者輸入文字用程式段的while迴圈為 while(1) { ZeroMemory(str, BUF_SIZE); cout << "you key in :"; cin.getline(str, BUF_SIZE); //向服務器發送數據 ZeroMemory(buf, BUF_SIZE); strcpy_s(buf, str); retVal = send(sHost, buf, strlen(buf), 0); if (SOCKET_ERROR == retVal) { cout << "send failed!\n"; closesocket(sHost); //關閉Socket WSACleanup(); //釋放Socket資源 system("pause"); return -1; } cout <<"server echo : "; retVal = recv(sHost, buf, BUF_SIZE, 0); cout << buf << endl; //輸出由Server端傳送的字串 if (!strcmp(buf,"bye")) break; } 最後發現cin.getline的指令疑似被略過 client及server端變成如圖片 http://i.imgur.com/31lho1j.jpg
http://i.imgur.com/1gy0EDA.jpg
餵入的資料(Input): 預期的正確結果(Expected Output): please key in IP:36.227.47.199 you key in :hello world server echo:hello world 錯誤結果(Wrong Output): 如上 程式碼(Code):(請善用置底文網頁, 記得排版) http://ideone.com/rbt8e7 http://ideone.com/YIvrfH 補充說明(Supplement): 請鞭小力點(跪 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.227.47.199 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1479530614.A.0D8.html ※ 編輯: airawesu (36.227.47.199), 11/19/2016 12:44:57

11/19 13:29, , 1F
會不會是卡在 connect,server 連不上
11/19 13:29, 1F

11/19 17:51, , 2F
先用wireshark看連線有沒有正常送出
11/19 17:51, 2F

11/19 18:05, , 3F
socket 出問題不一定是出在程式上
11/19 18:05, 3F

11/19 18:06, , 4F
wireshark 或 tcpdump 之類的 sniffer 確實會有需要
11/19 18:06, 4F

11/19 21:25, , 5F
你應該是參考網路上XYZ那篇寫的 先把main一開始就包進
11/19 21:25, 5F

11/19 21:26, , 6F
while迴圈就可以一直輸入了
11/19 21:26, 6F
我很確定SERVER可以連上 把整個main內的程式都包進去嗎 我現在還不行Q_Q ※ 編輯: airawesu (36.227.47.199), 11/19/2016 23:17:40 現在可以了 不修改while迴圈位置 我把cin>>IP_char; 改成cin.getline(IP_char,17); 功能就OK了 可正常使用 但有大神知道這是為什麼嗎 http://i.imgur.com/g6FJh0w.jpg
※ 編輯: airawesu (36.227.47.199), 11/19/2016 23:27:01

11/20 06:08, , 7F
數值與字串
11/20 06:08, 7F
我蠢透了 ※ 編輯: airawesu (114.136.26.93), 11/20/2016 08:59:22
文章代碼(AID): #1OBzXs3O (C_and_CPP)
文章代碼(AID): #1OBzXs3O (C_and_CPP)