端口号随便写了一个,写的是 2345。
如果需要按下Q键退出,客户端部分加个判断即可
服务端:
#include <iostream>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
using std::cout;
using std::endl;
int main()
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "WSA Error" << endl;
return 0;
}
sockaddr_in sd;
sd.sin_family = AF_INET;
sd.sin_port = htons(2345);
sd.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
// socket
SOCKET fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == INVALID_SOCKET)
{
cout << "socket error" << endl;
return 0;
}
// bind
if (bind(fd, (sockaddr *)(&sd), sizeof(sd)) == SOCKET_ERROR)
{
cout << "bind error" << endl;
return 0;
}
// listen
listen(fd, 10);
sockaddr_in sd2;
int sd2Size = sizeof(sd2);
// accept
SOCKET clientFd = accept(fd, (sockaddr *)(&sd2), &sd2Size);
if (clientFd == INVALID_SOCKET)
{
cout << "客户端 socket error" << endl;
}
char buf[1024] = "";
while (1)
{
if (recv(clientFd, buf, 1024, 0) != 0)
{
cout << "recv " << buf << endl;
send(clientFd, buf, 1024, 0);
// strcpy(buf, "");
}
}
closesocket(clientFd);
closesocket(fd);
WSACleanup();
return 0;
}
客户端:
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using std::cout;
using std::endl;
using std::cin;
int main()
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "WSA Error" << endl;
return 0;
}
// socket
SOCKET fd = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
if (fd == INVALID_SOCKET)
{
cout << "socket error" << endl;
return 0;
}
sockaddr_in sd;
sd.sin_family = AF_INET;
sd.sin_port = htons(2345);
sd.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
// connect
if (connect(fd, (sockaddr *)(&sd), sizeof(sd)) == SOCKET_ERROR)
{
cout << "connect error" << endl;
return 0;
}
while (1)
{
char buf[1024];
cout << "请输入数据:" << endl;
cin >> buf;
send(fd, buf, 1024, 0);
if (recv(fd, buf, 1024, 0) > 0)
{
cout << buf << endl;
}
}
closesocket(fd);
WSACleanup();
getchar();
return 0;
}