socket中的send和recv怎么用

 我来答
化清和
2016-12-22 · 建造师
化清和
采纳数:2256 获赞数:6975

向TA提问 私信TA
展开全部

MSDN中就有例子,给你贴上。

C/C++ code

#include <stdio.h>

#include "winsock2.h"

 

void main() {

  //----------------------

  // Initialize Winsock

  WSADATA wsaData;

  int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);

  if (iResult != NO_ERROR)

    printf("Error at WSAStartup()\n");

 

  //----------------------

  // Create a SOCKET for connecting to server

  SOCKET ConnectSocket;

  ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

  if (ConnectSocket == INVALID_SOCKET) {

    printf("Error at socket(): %ld\n", WSAGetLastError());

    WSACleanup();

    return;

  }

 

  //----------------------

  // The sockaddr_in structure specifies the address family,

  // IP address, and port of the server to be connected to.

  sockaddr_in clientService; 

  clientService.sin_family = AF_INET;

  clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );

  clientService.sin_port = htons( 27015 );

 

  //----------------------

  // Connect to server.

  if ( connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) {

    printf( "Failed to connect.\n" );

    WSACleanup();

    return;

  }

 

  //----------------------

  // Declare and initialize variables.

  int bytesSent;

  int bytesRecv = SOCKET_ERROR;

  char sendbuf[32] = "Client: Sending data.";

  char recvbuf[32] = "";

 

  //----------------------

  // Send and receive data.

  bytesSent = send( ConnectSocket, sendbuf, strlen(sendbuf), 0 );

  printf( "Bytes Sent: %ld\n", bytesSent );

 

  while( bytesRecv == SOCKET_ERROR ) {

    bytesRecv = recv( ConnectSocket, recvbuf, 32, 0 );

    if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) {

      printf( "Connection Closed.\n");

      break;

    }

    printf( "Bytes Recv: %ld\n", bytesRecv );

  }

 

  WSACleanup();

  return;

}

本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式