1、TcpServer(Tcp服务端)代码,适用于初学者学习
2、可配套NetAssist网络调试工具,开客户端收发测试
3、windows下使用,本人工具vs2015
代码:
// TcpServer.cpp : 定义控制台应用程序的入口点。
//
#include <stdio.h>
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
SOCKET slisten;
SOCKET sClient;//socket客户端
sockaddr_in remoteAddr;
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(sockVersion, &wsaData) != 0)
{
return 0;
}
//创建套接字
slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (slisten == INVALID_SOCKET)
{
printf("socket error !");
return 0;
}
//绑定IP和端口
sockaddr_in sin;
sin.sin_family = AF_INET;
//port最好1024以上,必须65535以下
sin.sin_port = htons(12345);
//使用自己主机的地址,请使用以下三种
//sin.sin_addr.S_un.S_addr = INADDR_ANY;
sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//sin.sin_addr.S_un.S_addr = inet_addr("192.168.1.100");
if (::bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
printf("bind error !");
return -1;
}
//开始监听
if (listen(slisten, 1) == SOCKET_ERROR)
{
printf("listen error !");
return -1;
}
int nAddrlen = sizeof(remoteAddr);
std::cout << "wait for accept" << std::endl;
sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
if (sClient == INVALID_SOCKET)
{
printf("accept error!");
return -1;
}
else
{
printf("accept success\n");
}
//接收Buff申请内存
char cBuff[5500];
while (1)
{
//接收Buff重置内存
memset(&cBuff, 0, 5500);
int ret = recv(sClient, cBuff, 5500, 0);
if (ret == SOCKET_ERROR || ret == 0)
break;
//打印Buff内容
printf("ret=%d, %s\n", ret, cBuff);
}
closesocket(sClient);
WSACleanup();
getchar();
return 0;
}