C++socket编程(三):3.9 TCPServer移植到windows中

本文介绍了如何将C++编写的TCPServer从其他平台移植到Windows,重点解决了在Windows中socket_t类型不适用以及由于std命名空间中的bind接口与系统接口冲突的问题。通过使用全局的::bind接口来避免命名冲突。
摘要由CSDN通过智能技术生成

如下代码:

#ifdef WIN32
#include <Windows.h>
#define socklen_t int
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#define closesocket close
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <thread>

using namespace std;

class TcpThread
{
public:
	void Main()
	{
		char buffer[1024] = { 0 };

		for (;;)
		{
			int recvlen = recv(client, buffer, sizeof(buffer) - 1, 0);  //第四个参数这个0是flag和系统相关,有很多自定一的操作,我们这边0就是不对他设置

			if (recvlen <= 0)
				break;

			buffer[recvlen] = '\0';

			if (strstr(buffer, "quit") != NULL)
			{
				char re[] = "quit success!\n";
				send(client, re, strlen(re) + 1, 0);
				break;
			}

			int sendlen = send(client, "ok\n", 4, 0);     //参数分析,第三个参数设置三个字节,第四个参数flag和操作系统有关,这里先写为0

			printf("recv %s\n", buffer);
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值