简单的socket编程入门示例

功能简单实现client输入内容发送到server端输出

复制代码 代码如下:

#include
#include
#include
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
 // 初始化 Winsock.
 WSADATA wsaData;
 int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
 if ( iResult != NO_ERROR )
 {
  cout<<"failed to initialize!"<  return 0;
 }

 // 建立socket socket.
 SOCKET client;
 client = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
 if ( client == INVALID_SOCKET )
 {
  cout<<"failed to create client socket!"<  WSACleanup();
  return 0;
 }

 // 连接到服务器.
 sockaddr_in clientService;
 clientService.sin_family = AF_INET;
 clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
 clientService.sin_port = htons( 13579 );

 if ( connect( client, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR)
 {
  cout<<"Failed to connect"<  closesocket(client);
  WSACleanup();
  return 0;
 }

 // 发送数据.
 int bytesSent;
 char sendbuf[4096] = "Client: Sending data.";
 while(TRUE)
 {
  bytesSent = send( client, sendbuf, strlen(sendbuf), 0 );
  gets_s(sendbuf, 4096);
 }

 closesocket(client);
 WSACleanup();
 return 0;
}

复制代码 代码如下:

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

using namespace std;

int main()
{
 WSADATA wsaData;

 int iInit = WSAStartup(MAKEWORD(2, 2), &wsaData);
 if (iInit != NO_ERROR)
 {
  cout<<"failed to initialize!"<  return 0;
 }

 SOCKET server = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if (server == INVALID_SOCKET)
 {
  cout<<"failed to create server socket!"<  WSACleanup();
  return 0;
 }

 sockaddr_in bindinfo;
 bindinfo.sin_family = AF_INET;
 bindinfo.sin_addr.s_addr =  inet_addr( "127.0.0.1" );
 bindinfo.sin_port = htons(13579);
 if ( bind( server, (SOCKADDR*) &bindinfo, sizeof(bindinfo) ) == SOCKET_ERROR )
 {
  cout<<"failed to bind!"<  closesocket(server);
  WSACleanup();
  return 0;
 }

 //listen
 if (listen(server, 1) == SOCKET_ERROR) {
  cout<<"listen failed"<  closesocket(server);
  WSACleanup();
  return 0;
 }

 //accept and block
 SOCKET socketWork = accept(server, NULL, NULL);
 if (socketWork == INVALID_SOCKET) {
  wprintf(L"accept failed with error: %ld\n", WSAGetLastError());
  closesocket(server);
  WSACleanup();
  return 0;
 }

 int byteRecv = SOCKET_ERROR;
 char recvBuf[4096] = "";

 while(TRUE)
 {
  byteRecv = recv(socketWork, recvBuf, 4096, 0);
  if (byteRecv == 0)
  {
   break;
  }
  recvBuf[byteRecv] = 0;
  cout< }

 closesocket(server);
 WSACleanup();
 return 0;
}

你可能感兴趣的:(简单的socket编程入门示例)