TCP通信C++实现

TCP客户端与服务器端通信模型:

服务器端实现:
#include<iostream>
#include <Winsock2.h>
#pragma comment(lib,"WS2_32")
using namespace std;
void main()
{
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
 wVersionRequested = MAKEWORD( 1, 1 );
 
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
  return;
 }
 
 if ( LOBYTE( wsaData.wVersion ) != 1 ||
        HIBYTE( wsaData.wVersion ) != 1 ) {
  WSACleanup( );
  return;
 }

 SOCKET fd,fd_client;
 struct sockaddr_in addr_server,addr_client;
 char buf[100];
 fd=socket(AF_INET,SOCK_STREAM,0); //创建监听套接字
 addr_server.sin_family=AF_INET;
 addr_server.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
 addr_server.sin_port=htons(6000);
 bind(fd,(sockaddr *)&addr_server,sizeof(addr_server));
 listen(fd,5);
 int len=sizeof(sockaddr);
 while(1)
 {
  fd_client=accept(fd,(sockaddr *)&addr_client,&len);
    recv(fd_client,buf,100,0); 
  cout<<buf<<endl;
  send(fd_client,"server:nihao",100,0); //发送数据
  closesocket(fd_client);
 }
}
客户端实现:
#include<iostream>
#include <Winsock2.h>
#pragma comment(lib,"WS2_32")
using namespace std;
void main()
{
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
 wVersionRequested = MAKEWORD( 1, 1 );
 
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
  return;
 }
 
 if ( LOBYTE( wsaData.wVersion ) != 1 ||
        HIBYTE( wsaData.wVersion ) != 1 ) {
  WSACleanup( );
  return;
 }
 SOCKET fd;
 struct sockaddr_in addr;
 char buf[100]="client:nihao";
 fd=socket(AF_INET,SOCK_STREAM,0);
 addr.sin_family=AF_INET;
 addr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
 addr.sin_port=htons(6000);
    connect(fd,( sockaddr *)&addr,sizeof(addr));
 send(fd,buf,100,0);
 recv(fd,buf,100,0);
 cout<<buf<<endl;
 closesocket(fd);
}

你可能感兴趣的:(C++,socket,Stream,tcp,server,服务器)