程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> 簡略的socket編程入門示例

簡略的socket編程入門示例

編輯:關於C++

簡略的socket編程入門示例。本站提示廣大學習愛好者:(簡略的socket編程入門示例)文章只能為提供參考,不一定能成為您想要的結果。以下是簡略的socket編程入門示例正文


功效簡略完成client輸出內容發送到server端輸入


#include <stdio.h>
#include <iostream>
#include <winsock2.h>
#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!"<<endl;
  return 0;
 }

 // 樹立socket socket.
 SOCKET client;
 client = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
 if ( client == INVALID_SOCKET )
 {
  cout<<"failed to create client socket!"<<endl;
  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"<<endl;
  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 <iostream>
#include <WinSock2.h>
#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!"<<endl;
  return 0;
 }

 SOCKET server = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if (server == INVALID_SOCKET)
 {
  cout<<"failed to create server socket!"<<endl;
  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!"<<endl;
  closesocket(server);
  WSACleanup();
  return 0;
 }

 //listen
 if (listen(server, 1) == SOCKET_ERROR) {
  cout<<"listen failed"<<endl;
  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<<recvBuf<<endl;
 }

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved