为啥我这个服务器代码老出问题(部分参考博主的代码)
#include "windows.h"
#include "iostream"
#include "process.h"
#include <string>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
void Receive(void* param)
{
while (1)
{
//客户端接受来自服务器的数据
SOCKET clientSocket = *(SOCKET*)(param);
char recvbuf[2048] = {}; //接收缓冲区
if (recv(clientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败" << endl;
}
else
cout << "【服务器】说:" << recvbuf << endl;
}
}
void Send(void* param)
{
while (1)
{
//客户端发送数据给服务器
SOCKET clientSocket = *(SOCKET*)(param);
char sendbuf[2048] = {}; //发送缓冲区
cin.getline(sendbuf, 2048);
if (send(clientSocket, sendbuf, strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!";
}
else
cout << "【自己】说:" << sendbuf << endl;
}
}
int main()
{
cout << "-----------客户端-----------" << endl;
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "套接字初始化失败!" << endl;
}
SOCKET clientSocket;
if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout << "套接字创建失败!" << endl;
}
struct sockaddr_in SeverAddress; //服务器地址 也就是即将要连接的目标地址
memset(&SeverAddress, 0, sizeof(sockaddr_in));
SeverAddress.sin_family = AF_INET;
SeverAddress.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //127.0.0.1表示本机ip地址
SeverAddress.sin_port = htons(5000);//设定端口号
//开始连接
if (connect(clientSocket, (sockaddr*)&SeverAddress, sizeof(SeverAddress)) == SOCKET_ERROR)
{
cout << "客户端:和服务器连接失败!" << endl;
return 0;
}
else
cout << "与服务器连接成功!" << endl;
//创建两个子线程
_beginthread(Receive, 0, &clientSocket);
//_beginthread(Send, 0, &clientSocket);
Sleep(INFINITE); //这里采用另外一种技术避免主线程执行完退出——使其无限期休眠
// 关闭socket
if (clientSocket != INVALID_SOCKET) {
closesocket(clientSocket);
clientSocket = INVALID_SOCKET;
}
// 终止
WSACleanup();
cout << "客户端退出!" << endl;
return 0;
}
期待你的回答