Server端设计:
1.初始化套接字版本:
- //初始化套接字版本 2.2
- WSADATA wsaData;
- WORD wVersion = MAKEWORD(2,2);
- int err = WSAStartup(wVersion,&wsaData);
- if(err != 0)
- return FALSE;
2.建立TCP套接字并处于监听状态:
- //填充本地地址信息
- SOCKADDR_IN addrSer;
- memset(&addrSer,0,sizeof(addrSer));
- addrSer.sin_family = AF_INET;
- addrSer.sin_port = htons(m_nPort);
- addrSer.sin_addr.s_addr = inet_addr("10.1.17.212");
- //建立套接字
- m_Listen =socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
- if (m_Listen == SOCKET_ERROR)
- return ;
- //绑定本地地址
- if (bind(m_Listen,(SOCKADDR*)&addrSer,sizeof(SOCKADDR)) != 0)
- return;
- //监听
- if (listen(m_Listen,SOMAXCONN) != 0)
- return ;
- //等待用户连接
- while(1)
- {
- SOCKET ClientSock = accept(m_Listen,NULL,NULL);
- if(ClientSock == SOCKET_ERROR)
- {
- //退出
- }
- //发送信息
- send(ClientSock,"Hello!",7,0);
- TCHAR szBuf[MAX_PATH] = {0};
- //接收对方发送来的信息
- int nRecv = recv(ClientSock,(char*)szBuf,MAX_PATH*sizeof(TCHAR),0);
- //其他..
- }
Client端设计:
- //version 2.2
- WSADATA wsaData;
- WORD wVersion = MAKEWORD(2,2);
- int err = WSAStartup(wVersion,&wsaData);
- if(err != 0)
- return FALSE;
- SOCKADDR_IN addrClient,addrSer;
- 建立
- SOCKET m_Client = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
- //填充本地地址
- memset(&addrClient,0,sizeof(SOCKADDR));
- addrClient.sin_family = AF_INET;
- addrClient.sin_port = htons(8080);
- addrClient.sin_addr.s_addr = inet_addr("127.0.0.1");
- //绑定本地地址,客户端可以不绑定
- int nRet = bind(m_Client,(SOCKADDR*)&addrClient,sizeof(SOCKADDR));
- //填充Server地址
- memset(&addrSer,0,sizeof(addrSer));
- addrSer.sin_family = AF_INET;
- addrSer.sin_port = htons(6060);
- addrSer.sin_addr.s_addr = inet_addr("127.0.0.1");
- //建立连接请求
- nRet = connect(m_Client,(SOCKADDR*)&addrSer,sizeof(SOCKADDR));
- if (nRet != 0)
- return ;
- TCHAR szBuf[MAX_PATH] = {_T("Hello!")};
- nRet = send(m_Client,(char*)szBuf,MAX_PATH*sizeof(TCHAR),0);
- if(nRet == SOCKET_ERROR)
- //发送失败
- int nRecv = recv(m_Client,(char*)szBuf,MAX_PATH*sizeof(TCHAR),0);
- //显示...
现在建立好的服务端和客户端都是阻塞式通信,TCP通信基本内容就是首先建立套接字,然后服务端处于监听状态等待用户连接,连接完成后就可以开始通信了。今天先写到这儿吧,明天写UDP阻塞式通信的建立。