欢迎来到代码驿站!

C代码

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

简单的socket编程入门示例

时间:2021-01-15 11:15:29|栏目:C代码|点击:

功能简单实现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;
}

上一篇:C语言读取文件流的相关函数用法简介

栏    目:C代码

下一篇:解析C语言与C++的编译模型

本文标题:简单的socket编程入门示例

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

推荐教程

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

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

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

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

Copyright © 2020 代码驿站 版权所有