版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、精選優(yōu)質(zhì)文檔-傾情為你奉上實(shí)驗(yàn)報(bào)告實(shí)驗(yàn)課程名稱: 通信軟件基礎(chǔ)實(shí)驗(yàn)課 學(xué) 院: 軟件工程學(xué)院 專 業(yè): 軟件工程 指導(dǎo)教師: 報(bào)告人姓名: 學(xué) 號: 班 級: 學(xué) 期: 實(shí)驗(yàn)成績實(shí)驗(yàn)項(xiàng)目名稱基于WinSock的簡單TCP網(wǎng)絡(luò)編程一、實(shí)驗(yàn)?zāi)康呐c要求:1、學(xué)習(xí)和掌握Socket編程的面向連接編程模型。2、學(xué)習(xí)和掌握基于WinSock的TCP網(wǎng)絡(luò)編程方法。二、實(shí)驗(yàn)設(shè)備及軟件:筆記本電腦、Window 7操作系統(tǒng)、Microsoft Visual Studio 2012三、實(shí)驗(yàn)方法(原理、流程圖)流程圖:四、實(shí)驗(yàn)過程、步驟及內(nèi)容實(shí)驗(yàn)代碼:server.h#define MAX_CLIENT 10/同時(shí)
2、服務(wù)的client數(shù)目上限#define MAX_BUF_SIZE 65535/緩存區(qū)的大小const u_short UDPSrvPort= 2345;/Server的UDP端口const char START_CMD= START;const char GETCURTIME_CMD= GET CUR TIME;/傳遞給TCP線程的結(jié)構(gòu)化參數(shù)struct TcpThreadParamSOCKET socket;sockaddr_in addr;DWORD WINAPI TcpServeThread(LPVOID lpParam);/TCP線程的線程函數(shù)DWORD WINAPI UdpServ
3、er(LPVOID lpParam);/UDP服務(wù)器線程server.cpp#include stdafx.h#include iostream.h#include stdio.h#include string.h#include time.h#include WinSock2.h#include Windows.h#include server.h#pragma comment (lib, Ws2_32.lib)#pragma pack(1)/結(jié)構(gòu)在存儲時(shí)按字節(jié)對齊long TcpClientCount = 0;int main(int argc, char* argv)/檢查命令行參數(shù)/i
4、f(argc != 2)/cerr Worng format!nCorrect usage: Server.exe ;/return -1;/初始化winsock2環(huán)境WSADATA wsa;if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)cerr nFailed to initialize the winsock 2 stackn error code: WSAGetLastError() h_addr_list0;/綁定TCP端口if (bind(ListenSocket, (sockaddr*)&ListenAddr, sizeof(ListenAdd
5、r) = SOCKET_ERROR)cerr nFailed to bind the ListenSocketn error code: WSAGetLastError() endl;return -1;/監(jiān)聽if (listen(ListenSocket, SOMAXCONN) = SOCKET_ERROR)cerr nFailed to listen the ListenSocketn error code: WSAGetLastError() endl;return -1;cout TCP Server Started On TCP Port: ListenPort endl endl;
6、SOCKET TcpSocket;SOCKADDR_IN TcpClientAddr;while (TRUE)/接受客戶端連接請求int iSockAddrLen = sizeof(sockaddr);if (TcpSocket = accept(ListenSocket, (sockaddr*)&TcpClientAddr, &iSockAddrLen) = SOCKET_ERROR)cerr nFailed to accept the client TCP Socketn error code: WSAGetLastError() = MAX_CLIENT)closesocket(TcpS
7、ocket);cout Connection from TCP client inet_ntoa(TcpClientAddr.sin_addr) : ntohs(TcpClientAddr.sin_port) refused for max client numn endl;continue;cout Connection from TCP client inet_ntoa(TcpClientAddr.sin_addr) : ntohs(TcpClientAddr.sin_port) acceptedn endl;TcpThreadParam Param;Param.socket = TcpS
8、ocket;Param.addr = TcpClientAddr;/創(chuàng)建TCP服務(wù)線程DWORD dwThreadId;CreateThread(NULL, 0, TcpServeThread, &Param, 0, &dwThreadId);InterlockedIncrement(&TcpClientCount);cout Current Number of TCP Clients: TcpClientCount n socket;SOCKADDR_IN TcpClientAddr = (TcpThreadParam*)lpParam)-addr;/輸出提示信息coutThread: Ge
9、tCurrentThreadId() is serving client from inet_ntoa(TcpClientAddr.sin_addr) : ntohs(TcpClientAddr.sin_port) endl endl;/發(fā)送端口號+STARTsprintf(ServerTCPBuf, %5d%s, UDPSrvPort, START_CMD);send(TcpSocket, ServerTCPBuf, strlen(ServerTCPBuf), 0);cout Waiting for command from Client(s). endl endl;int TCPBytes
10、Received;time_t CurSysTime;while (TRUE)/讀取client發(fā)來的請求命令: GET CUR TIMEmemset(ServerTCPBuf, 0, sizeof(ServerTCPBuf);TCPBytesReceived = recv(TcpSocket, ServerTCPBuf, sizeof(ServerTCPBuf), 0);/TCPBytesReceived值為0表示client端已正常關(guān)閉連接/TCPBytesRecieved值為SOCKET_ERROR則表示socket的狀態(tài)不正常,無法繼續(xù)數(shù)據(jù)通訊/兩種情況下都表明本線程的任務(wù)已結(jié)束,需要
11、退出if (TCPBytesReceived = 0 | TCPBytesReceived = SOCKET_ERROR)cout Client from inet_ntoa(TcpClientAddr.sin_addr) : ntohs(TcpClientAddr.sin_port) disconnected. Thread: GetCurrentThreadId() is ending endl endl;break;/檢查收到的字符串是否為命令:GET CUR TIMEif (strcmp(ServerTCPBuf, GETCURTIME_CMD) != 0)cout Unknowm c
12、ommand from Client inet_ntoa(TcpClientAddr.sin_addr) endl endl;continue;cout Request for Current time from client inet_ntoa(TcpClientAddr.sin_addr) : ntohs(TcpClientAddr.sin_port) by TCP endl endl;/獲取系統(tǒng)時(shí)間并發(fā)送給clienttime(&CurSysTime);memset(ServerTCPBuf, 0, sizeof(ServerTCPBuf);strftime(ServerTCPBuf,
13、sizeof(ServerTCPBuf), %Y-%m-%d %H:%M:%S, localtime(&CurSysTime);send(TcpSocket, ServerTCPBuf, strlen(ServerTCPBuf), 0);cout Server Current Time: ServerTCPBuf n h_addr_list0;/綁定UDP端口if (bind(UDPSrvSocket, (sockaddr*)&UDPSrvAddr, sizeof(UDPSrvAddr) = SOCKET_ERROR )cerr bind() failed for UDPSrvSocketn
14、error code: WSAGetLastError() endl;return -1;coutUDP Server Started On UDP Port: UDPSrvPort endl endl;while (TRUE)memset(ServerUDPBuf, 0, sizeof(ServerUDPBuf);/接收UDP請求int iSockAddrLen = sizeof(sockaddr);if (recvfrom(UDPSrvSocket, ServerUDPBuf, sizeof(ServerUDPBuf), 0, (sockaddr*)&UDPClientAddr, &iSo
15、ckAddrLen) = SOCKET_ERROR)cerr recvfrom() failed for UDPSrvSocketn error code: WSAGetLastError() endl;continue;cout Client Command: Echonn;cout ServerUDPBuf received from inet_ntoa(UDPClientAddr.sin_addr) : ntohs(UDPClientAddr.sin_port) by UDP endl endl;/ECHOiSockAddrLen = sizeof(sockaddr);if (sendt
16、o(UDPSrvSocket, ServerUDPBuf, strlen(ServerUDPBuf), 0, (sockaddr*)&UDPClientAddr, iSockAddrLen) = SOCKET_ERROR )cerr sendto() failed for UDPSrvSocketn error code: WSAGetLastError() endl;continue;cout Echo ServerUDPBuf to clinet inet_ntoa(UDPClientAddr.sin_addr) : ntohs(UDPClientAddr.sin_port) by UDP
17、 endl endl;return 0;client.exe#include stdafx.h#include WinSock2.h#include iostream.h #include stdio.h#pragma comment (lib,Ws2_32.lib)#define MAX_BUF_SIZE 65535char ClientBufMAX_BUF_SIZE;const char START_CMD= START;const char GETCURTIME_CMD= GET CUR TIME;/輸出用戶選擇界面void UserPrompt()cout Input the corr
18、esponding Num to select what you want the program to do endl endl t1. Get current time(TCP) endl t2. Echo Mode(UDP) endl t3. Exit the program endl endl Enter Your choice: ;int main(int argc, char* argv)unsigned short ServerUDPPort;SOCKET cTCPSocket,cUDPSocket;WSADATA wsadata;SOCKADDR_IN TCPServer,UD
19、PServer,RecvFrom;int RecvFromLength=sizeof(RecvFrom);char UserChoice;char portnum5;unsigned long BytesReceived,BytesSent;int RetValue;/檢查命令行參數(shù)if (argc != 3)coutWorng format!endlCorrect usage: Client.exe endl;return 1;u_long ServerIP = inet_addr(argv1);u_short ServerTCPPort = (u_short)atoi(argv2);/初始
20、化winsock庫if( ( RetValue=WSAStartup(MAKEWORD(2,2),&wsadata) ) !=0 )printf(WSAStartup() failed with error %dn, RetValue);return 2;/創(chuàng)建TCP Socketif( (cTCPSocket=WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED) ) =INVALID_SOCKET)printf(WSASocket() for cTCPSocket failed with error %dn ,WSAGetLa
21、stError() );return 3;/創(chuàng)建UDP Socketif( (cUDPSocket=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_OVERLAPPED) ) =INVALID_SOCKET)printf(WSASocket() for cUDPSocket failed with error %dn ,WSAGetLastError() );return 4;TCPServer.sin_family=AF_INET;TCPServer.sin_port=htons(ServerTCPPort);TCPServer.sin_addr
22、.S_un.S_addr=ServerIP;/通過TCP Socket連接serverif (RetValue=WSAConnect(cTCPSocket,(sockaddr *)&TCPServer,sizeof(TCPServer),NULL,NULL,NULL,NULL) )=SOCKET_ERROR)printf(WSAConnect() failed for cTCPSocket with error %dn,WSAGetLastError() );printf(Cant connect to server.n);return 5;/與server建立連接后讀取Server發(fā)送過來的
23、Server UDP端口和STARTBytesReceived=recv(cTCPSocket,ClientBuf,sizeof(ClientBuf),0 );if (BytesReceived = 0 | BytesReceived = SOCKET_ERROR)coutendlServer refused the connection or recv failedendl;return 6;memcpy(portnum,ClientBuf,sizeof(portnum);ServerUDPPort=(u_short)atoi(portnum);if (strcmp(START_CMD,Cl
24、ientBuf+5)!=0)coutendlServer did not return right beginning indicatorendl;return 6;elsecoutendlOK, NOW the server is ready for your service!endlUserChoice;switch(UserChoice)case 1:/通過TCP得到server的系統(tǒng)時(shí)間/發(fā)送命令memset(ClientBuf,0,sizeof(ClientBuf);sprintf(ClientBuf,%s,GETCURTIME_CMD);if (BytesSent=send(cTC
25、PSocket,ClientBuf,strlen(ClientBuf),0) )=SOCKET_ERROR)printf(send() failed for cTCPSocket with error %dn,WSAGetLastError() );printf(Can not send command to server by TCP.Maybe Server is down.n);return 7;/讀取server發(fā)來的系統(tǒng)時(shí)間并顯示memset(ClientBuf,0,sizeof(ClientBuf) );if (BytesReceived=recv(cTCPSocket,Clien
26、tBuf,sizeof(ClientBuf),0) )=SOCKET_ERROR)printf(recv() failed for cTCPSocket with error %dn,WSAGetLastError() );printf(Can not get server current systime.Maybe Maybe Server is down.n);return 8;coutServer Current Time: ClientBufendlendl;break;case 2: /通過UDP實(shí)現(xiàn)ECHO/提示用戶輸入文本memset(ClientBuf,0,sizeof(ClientBuf) );cout請輸入任意文本信息,按回車鍵后將發(fā)送至Server.endl;gets(ClientBuf);/發(fā)送文本if (BytesSent=sendto(cUDPSocket,ClientBuf,strlen(ClientBuf),0,(sockaddr *)&UDPServer,sizeof(UDPServer) ) ) =SOCKET_ERROR)printf(sendto() failed for cUDPSocket with error %
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 【小數(shù)-青島版(六三制)】三下第1單元 3 商中間或末尾有0的除法 教案(pdf版)
- 二年級下冊心理健康教育教案-第12課暑假指南針長春版
- 蘇少版四年級美術(shù)上冊《第8課 做做海洋生物》教學(xué)設(shè)計(jì)
- 安徽省蚌埠市第一中學(xué)2025年高三一輪復(fù)習(xí)單元檢測試題(三)化學(xué)試題含解析
- 建筑結(jié)構(gòu)質(zhì)量通病防治措施
- 爭創(chuàng)魯班獎(jiǎng)工程的相關(guān)知識
- 2024鐵路運(yùn)輸行業(yè)計(jì)量器具管理辦法
- 《針織塑身褲》征求意見稿
- 財(cái)務(wù)人年終述職報(bào)告范文8篇
- 2024運(yùn)動廣播稿(10篇)
- 亞太藥業(yè)信息披露違法違規(guī)案例分析
- 《高端會所模式營銷》課件
- 智慧樹知到《中國傳統(tǒng)文化(西安交通大學(xué))》章節(jié)測試答案
- 檢驗(yàn)科pcr科室出科小結(jié)
- 聯(lián)合辦公協(xié)議書范本
- 品牌建立計(jì)劃書
- 青少年藥物濫用的影響因素與預(yù)防方法
- 承債式股權(quán)收購協(xié)議書承債式股權(quán)收購協(xié)議書模板(三篇)
- 小學(xué)道德與法治課評分參考指標(biāo)
- 農(nóng)藝工技師高級理論及專業(yè)技術(shù)知識試題庫(含答案)
評論
0/150
提交評論