基于TCP协议的网络通信
利用SOCKET套接字实现客户端与服务器间的连接
1、 面向连接编程(TCP)
面向连接的网络应用程序开发流程比较固定,需要开发者创建服务器与客户端两个应用程序,通过网络实现进程间的通讯。
● 服务器端流程
① 创建套接字(socket)
② 服务绑定(bind)
③ 服务侦听(listen)
④ 处理新到连接(accept)
⑤ 数据收发(recv\send)
⑥ 套接字关闭(close)
● 客户端流程
① 客户端套接字创建(socket)
② 发起连接 (connect)
③ 数据发收(send\recv)
④ 套接字关闭(close)
CLIENT:
#include <windows.h> #include <string.h> using namespace std; #pragma comment(lib,"ws2_32.lib") void main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return; } if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); return; } SOCKET sockCli; sockCli = socket(AF_INET,SOCK_STREAM,0); SOCKADDR_IN addrSer; addrSer.sin_family = AF_INET; addrSer.sin_port = htons(5050); addrSer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); int res = connect(sockCli,(SOCKADDR*)&addrSer,sizeof(SOCKADDR)); if(res != 0) { cout<<"Client Connect Server Failed!"<<endl; } else { cout<<"Client Connect Server Success!"<<endl; } char sendbuf[256]; char recvbuf[256]; while(1) { recv(sockCli,recvbuf,256,0); cout<<"Server:> "<<recvbuf<<endl; cout<<"Client:> "; cin>>sendbuf; send(sockCli,sendbuf,strlen(sendbuf)+1,0); } closesocket(sockCli); WSACleanup(); }
SERVER:
#include <iostream> #include <windows.h> using namespace std; #pragma comment(lib,"ws2_32.lib") void main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return; } if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup( ); return; } SOCKET sockSer; sockSer = socket(AF_INET,SOCK_STREAM,0);//TCP/IP SOCKADDR_IN addrSer; SOCKADDR_IN addrCli; addrSer.sin_family = AF_INET; addrSer.sin_port = htons(5050);//host to net short addrSer.sin_addr.S_un.S_addr = inet_addr("192.168.0.144"); bind(sockSer,(SOCKADDR*)&addrSer,sizeof(SOCKADDR)); listen(sockSer,5); cout<<"Server Wait Client Connect"<<endl; SOCKET sockConn; int len = sizeof(SOCKADDR); sockConn = accept(sockSer,(SOCKADDR*)&addrCli,&len); if(sockConn == INVALID_SOCKET) { cout<<"Server Accept Client Connect failed"<<endl; closesocket(sockSer); WSACleanup(); return; } else { cout<<"Server Accept Client Connect Success!"<<endl; } char sendBuf[256]; char recvBuf[256]; while(1) { cout<<"Ser :> "; cin>>sendBuf; send(sockConn, sendBuf, 256, 0); recv(sockConn, recvBuf, 256, 0); cout<<"Cli :>"<<recvBuf<<endl; } closesocket(sockSer); WSACleanup(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-13 22:07:07