服务器之家

服务器之家 > 正文

vc++实现的tcp socket客户端和服务端示例

时间:2021-01-16 13:29     来源/作者:C++教程网

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();
}

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部