windows多客户端socket tcp通讯
程序员文章站
2024-03-23 09:40:04
...
#include <iostream>
#include <thread>
#include <string>
#include <WinSock2.h>
#include <Ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using std::cin;
using std::cerr;
using std::cout;
using std::endl;
using std::flush;
const int SEND_BUF_SIZE = 256;
bool b_running = true;
bool b_send = false;
//接收服务器返回的数据
void t_read_result(SOCKET sock_client){
int recv_result = 0;
char _buf[SEND_BUF_SIZE];
while (b_running) {
recv_result = recv(sock_client, _buf, SEND_BUF_SIZE, 0);
if (strlen(_buf) > 0) {
cout << "bytes: " << strlen(_buf) << " receive_msg: " << _buf << endl;//feedback from server
memset(_buf, 0, SEND_BUF_SIZE);
}
if (recv_result == 0) {
cout << "bytes: " << strlen(_buf) << " connection closed..." << endl;
}
if (recv_result < 0) {
cerr << "recv() function failed with error: " << WSAGetLastError() << "\n";
closesocket(sock_client);
WSACleanup();
system("pause");
return;
}
}
}
//向服务器发送数据
bool send_data(SOCKET client)
{
while (b_running){
std::string input;
cin >> input;
//int error=send(SOCKET s, const void * msg, int len, unsigned int flags)//send()用来将数据由指定的socket通信
//s为已建立好连接的socket,msg数据内容,len数据长度,参数flags一般设0
//成功则返回实际传送出去的字符数,失败返回-1,错误原因存于error
int result = send(client, input.c_str(), static_cast<int>(input.size()), 0);
if (SOCKET_ERROR == result)
{
int error = WSAGetLastError();//错误代码
if (WSAEWOULDBLOCK == error)
{
continue;
}
else if (WSAENETDOWN == error || WSAETIMEDOUT == error || WSAECONNRESET == error)
{
return false;
}
}
}
return true; //发送成功
}
int main()
{
WSADATA wsdata;
if (WSAStartup(MAKEWORD(2, 2), &wsdata) != 0)
{
return 0;
}
SOCKET client = socket(AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP);
if (client == INVALID_SOCKET)
{
printf("创建套接字失败!");
return 0;
}
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(1024);//串口(需与服务器一致)
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//IP
if (connect(client, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
{
printf("连接服务器失败!");
closesocket(client);
return 0;
}
std::thread read_result(t_read_result, std::ref(client));
read_result.detach();
send_data(client);
closesocket(client);
WSACleanup();
return 0;
}