服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - tcp socket客户端和服务端示例分享

tcp socket客户端和服务端示例分享

2021-01-17 16:17C语言程序设计 C/C++

这篇文章主要介绍了tcp socket客户端和服务端示例,需要的朋友可以参考下

以下是tcp socket客户端和服务端源码,代码简单大家参考使用吧

Tcp Server

复制代码 代码如下:


#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
// initial socket library
WORD wVerisonRequested;
WSADATA wsaData;
int err;
wVerisonRequested = MAKEWORD(1, 1);
err = WSAStartup(wVerisonRequested, &wsaData);
if (err != 0)
{
return -1;
}
//if (LOBYTE(wsaData.wVersion) != 1 ||
//HIBYTE(wsaData.wHighVersion) != 1)
//{
//WSACleanup();
//return -1;
//}

 

// create socket
SOCKET sockServer = socket(AF_INET, SOCK_STREAM, 0);

// bind socket
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
bind(sockServer, (SOCKADDR *)&addrServer, sizeof(addrServer));

// listen
listen(sockServer, 5);

SOCKADDR_IN addrClient;
int len = sizeof(addrClient);
while(1)
{
// accept
SOCKET sockConnection = accept(sockServer, (SOCKADDR *)&addrClient, &len);

// send
char sendBuf[100];
sprintf(sendBuf, "Welcome %s", inet_ntoa(addrClient.sin_addr));
send(sockConnection, sendBuf, strlen(sendBuf)+1,0);

// receive
char recvBuf[100];
recv(sockConnection, recvBuf, 100, 0);

//
printf("%s", recvBuf);

// close connection socket
closesocket(sockConnection);
}
}

 

Tcp Client

 

复制代码 代码如下:


#include <WinSock2.h>
#include <stdio.h>

 

#pragma comment(lib, "ws2_32.lib")

int main()
{
// initial socket library
WORD wVerisonRequested;
WSADATA wsaData;
int err;
wVerisonRequested = MAKEWORD(1, 1);
err = WSAStartup(wVerisonRequested, &wsaData);
if (err != 0)
{
return -1;
}
//if (LOBYTE(wsaData.wVersion) != 1 ||
//HIBYTE(wsaData.wHighVersion) != 1)
//{
//WSACleanup();
//return -1;
//}

// create socket
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);

// connect server socket
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
connect(sockClient, (SOCKADDR *)&addrServer, sizeof(addrServer));

// receive
char recvBuf[100];
recv(sockClient, recvBuf, 100, 0);

//
printf("%s", recvBuf);

// send
char sendBuf[100] = "this is lisi\n";
send(sockClient, sendBuf, strlen(sendBuf)+1,0);

// close connection socket
closesocket(sockClient);

// clean socket library
WSACleanup();
}

 

延伸 · 阅读

精彩推荐