说明:之前在CSDN上找TCP编程时,发现有各种版本。不同版本之间写法不一,所以自己写了个C语言版本的,记录下来。
服务端代码:
/**
* TCP服务端通信
* date:21/8/31
* 注意:测试时,先启动服务端,再启动客户端!
* */
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib, "Ws2_32.lib")
#include<stdio.h>
#include<WinSock2.h>
#include<ws2tcpip.h>
int main(int argc, char* argv[]) {
printf("This is server:\n");
//初始化dll
//当正确初始化时,WSAStartup会返回0
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (ret != 0) { printf("ret报错 %d\n", ret); }
//1、创建tcp套接字
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//2、绑定套接字 bind
//返回值为0时表示绑定成功
//SOCKADDR_IN等同于struct sockaddr_in
SOCKADDR_IN serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(1324);
int ret2 = bind(sock, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
if (ret2 != 0) { printf("ret2报错 %d\n", ret2); }
//3、监听listen
//成功返回0, 失败返回-1.
int ret3 = listen(sock, 20);
if (ret3 != 0) { printf("ret3报错 %d\n", ret3); }
while (1)
{
//4、接收客户端连接accept
SOCKADDR cAddr;
int nSize = sizeof(SOCKADDR);
SOCKET accSock = accept(sock, (SOCKADDR*)&cAddr, &nSize);
//5、接收消息
char buf[1024] = { 0 };
int ret4 = recv(accSock, buf, 1024, 0);
if (ret4 > 0) { printf("接受到消息:%s\n", buf); }
if (ret4 <= 0) { printf("ret4报错 %d\n", ret4); }
//6、发消息
char* str = "This is server,Hello client!";
int ret5 = send(accSock, str, strlen(str), 0);
if (ret5 <= 0) { printf("ret5 %d\n", ret5); }
if (ret5 >0) { printf("server发送成功!发送的字节数为 %d\n", ret5); }
}
//7、关闭套接字
closesocket(sock);
//关闭winsock服务
WSACleanup();
return 0;
}
客户端代码:
/**
* TCP客户端通信
* date:21/8/31
* */
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib, "Ws2_32.lib")
#include<stdio.h>
#include<WinSock2.h>
#include <WS2tcpip.h>
int main(int argc,char* argv[]) {
printf("This is client:\n");
//初始化DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//1、创建tcp套接字
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//2、连接服务器
struct sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
sockAddr.sin_port = htons(1324);
//connect连接成功
if (connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) != -1)
{
//3、发消息
int ret = send(sock, "This is client, hello server!", strlen("This is client, hello server!"), 0);
if (ret > 0) { printf("client发送成功!发送的字节数为:%d\n",ret); }
if (ret < 0) { printf("client发送失败!ret %d\n",ret); }
//4、收消息
char buffer[1024] = { 0 };
if (recv(sock, buffer, 1024, 0) > 0) {
printf("接受到消息: %s\n", buffer);
}
}
//关闭套接字
closesocket(sock);
//终止使用 DLL
WSACleanup();
//保证主线程不提前结束
getchar();
return 0;
}