以下代码是TCP协议在winsocket下的实现,在vs2013下运行有效。
服务器部分代码:
#include
#include
#pragma comment(lib, "ws2_32.lib")
int main()
{
/*------------定义变量------------*/
char sendBuff[100], recvBuff[100]; //定义发送和接受字符串数组
int sendLen, recvLen; //定义发送和接受字符长度
SOCKET socketSend; //定义套接字
SOCKADDR_IN srvAddr; //服务器地址信息结构体
WORD wVersionRequest; //unsigned short
WSADATA wsaData; //winsocket 版本信息
int error; //定义错误
/*---------初始化套接字库---------*/
//定义版本类型,将两个字节组合成一个网络字节序,前面是低字节,后面是高字节(网络字节序采用高字节序,CPU采用低字节序)
wVersionRequest = MAKEWORD(2, 2);
if (WSAStartup(wVersionRequest, &wsaData) != 0)
{
printf("套接字版本库初始化失败!\n");
}
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
printf("版本不符!\n");
WSACleanup();
return 0;
}
/*---------设置服务器地址---------*/
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
srvAddr.sin_port = htons(8888);
/*-----------创建套接字-----------*/
socketSend = socket(AF_INET, SOCK_STREAM, 0);
/*-----向服务器发出connect连接----*/
if (connect(socketSend, (SOCKADDR *)&srvAddr, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
printf("连接失败!\n");
}
while (1)
{
/*------发送数据-------*/
printf("Please Enter Message:\n");
//scanf_s("%s", sendBuff, 100);
gets_s(sendBuff, 100);
if (send(socketSend, sendBuff, 100, 0) < 0)
{
printf("发送失败!\n");
}
/*------接收数据-------*/
if (recv(socketSend, recvBuff, 100, 0) < 0)
{
printf("接收失败!\n程序退出\n");
break;
}
else
{
printf("Server says:%s\n", recvBuff);
}
}
closesocket(socketSend);
WSACleanup();
return 0;
}
客户端部分代码:
#include
#include
#pragma comment(lib, "ws2_32.lib")
int main()
{
/*------------定义变量------------*/
char sendBuff[100], recvBuff[100]; //定义发送和接受字符串数组
int sendLen, recvLen; //定义发送和接受字符长度
SOCKET socketSend; //定义套接字
SOCKADDR_IN srvAddr; //服务器地址信息结构体
WORD wVersionRequest; //unsigned short
WSADATA wsaData; //winsocket 版本信息
int error; //定义错误
/*---------初始化套接字库---------*/
//定义版本类型,将两个字节组合成一个网络字节序,前面是低字节,后面是高字节(网络字节序采用高字节序,CPU采用低字节序)
wVersionRequest = MAKEWORD(2, 2);
if (WSAStartup(wVersionRequest, &wsaData) != 0)
{
printf("套接字版本库初始化失败!\n");
}
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
printf("版本不符!\n");
WSACleanup();
return 0;
}
/*---------设置服务器地址---------*/
srvAddr.sin_family = AF_INET;
srvAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
srvAddr.sin_port = htons(8888);
/*-----------创建套接字-----------*/
socketSend = socket(AF_INET, SOCK_STREAM, 0);
/*-----向服务器发出connect连接----*/
if (connect(socketSend, (SOCKADDR *)&srvAddr, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
printf("连接失败!\n");
}
while (1)
{
/*------发送数据-------*/
printf("Please Enter Message:\n");
//scanf_s("%s", sendBuff, 100);
gets_s(sendBuff, 100);
if (send(socketSend, sendBuff, 100, 0) < 0)
{
printf("发送失败!\n");
}
/*------接收数据-------*/
if (recv(socketSend, recvBuff, 100, 0) < 0)
{
printf("接收失败!\n程序退出\n");
break;
}
else
{
printf("Server says:%s\n", recvBuff);
}
}
closesocket(socketSend);
WSACleanup();
return 0;
}