欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

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

时间:2021-03-31 09:13:05|栏目: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();
}

上一篇:归并排序的递归实现与非递归实现代码

栏    目:C代码

下一篇:C++设计模式之策略模式

本文标题:vc++实现的tcp socket客户端和服务端示例

本文地址:http://www.codeinn.net/misctech/91605.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有