Windows下面向连接的套接字通信

服务器端代码:

#include <stdio.h>
#include <Winsock2.h>
#include <windows.h>
DWORD WINAPI ReceiveData(LPVOID param);
void main()
{
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2),&wsaData);
if(ret){
printf("初始化windsock 2.2 网络库失败\n");
return;
}
SOCKADDR_IN servieAddr;
servieAddr.sin_family = AF_INET;
servieAddr.sin_addr.s_addr = inet_addr("192.168.0.115");
servieAddr.sin_port = htons(9000);
SOCKET listenSocket;
listenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET == listenSocket){
printf("初始化socket\n");
WSACleanup();
return;
}
ret = bind(listenSocket,(SOCKADDR*)&servieAddr,sizeof(servieAddr));
if(ret == SOCKET_ERROR){
printf("绑定监听套接字失败 err=%d\n",WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return;
}
ret = listen(listenSocket,1);
if(ret == SOCKET_ERROR){
printf("设置套接字为监听状态失败 err = \n",WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return;
}
SOCKADDR_IN clientAddr;
SOCKET clientSocket;
int clientLen = sizeof(clientAddr);
// 开启一个线程 让 listenSocket 等待一个连接
while(1){
clientSocket = accept(listenSocket,(SOCKADDR*)&clientAddr,&clientLen);
if(clientSocket == INVALID_SOCKET){
printf("设置accept失败 ret = %d\n",WSAGetLastError());
break;
}
else{
//接收接收到新的连接 开启一个线程接收数据
printf("接收到一个客户端的连接\n");
DWORD threadID;
HANDLE hThreadID;
hThreadID = CreateThread(0,0,ReceiveData,(void*)&clientSocket,0,&threadID);
if(hThreadID == NULL){
//
printf("接收到一个客户端连接,create接收线程失败");
}
}
}
closesocket(listenSocket);
if(( WSACleanup()== SOCKET_ERROR )){
printf("清理windsock 2.2 网络库失败\n");
return;
}
return;
}


DWORD WINAPI ReceiveData(LPVOID param){
char recvBuf[255];
memset(recvBuf,0,10);
SOCKET clientSocket = *(SOCKET*)param;
int ret = recv(clientSocket,recvBuf,255,0);
if(ret >0){
printf("接收到如下数据:%s\n",recvBuf);
}
closesocket(clientSocket);
return 0;
}


客户端:

WSADATA wsaData;
ret = WSAStartup(MAKEWORD(2,2),&wsaData);
if(ret){
return;
}
SOCKADDR_IN connServerAddr;
connServerAddr.sin_family = AF_INET;
connServerAddr.sin_addr.s_addr = inet_addr("192.168.0.115");
connServerAddr.sin_port = htons(9000);
SOCKET connSocket;
connSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET == connSocket){
closesocket(connSocket);
WSACleanup();
return;
}
ret = connect(connSocket,(SOCKADDR*)&connServerAddr,sizeof(connServerAddr));
if(ret == SOCKET_ERROR){
closesocket(connSocket);
WSACleanup();
return;
}
// 连接成功
char* buf="this is test client.....................";
ret = send(connSocket,buf,strlen(buf),0);
if(ret == SOCKET_ERROR){
closesocket(connSocket);
WSACleanup();
return;
}
closesocket(connSocket);
WSACleanup();

接下来如何定义 双方的通讯协议

你可能感兴趣的:(windows,tcp,socket,Stream,网络,winapi)