原文:在windows下用C语言写socket通讯实例

From:Microsoft Dev Center

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h> // Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib") #define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015" int __cdecl main(void)
{
WSADATA wsaData;
int iResult; SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET; struct addrinfo *result = NULL;
struct addrinfo hints; int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
printf("from server:\n");
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
} ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE; // Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
} // Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
} // Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
} freeaddrinfo(result); iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
} // Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
} // No longer need server socket
closesocket(ListenSocket); // Receive until the peer shuts down the connection
do { iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult); // Echo the buffer back to the sender
iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
if (iSendResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf("Bytes sent: %d\n", iSendResult);
}
else if (iResult == 0)
printf("Connection closing...\n");
else {
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
} } while (iResult > 0); // shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
} // cleanup
closesocket(ClientSocket);
WSACleanup(); return 0;
}
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h> // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib") #define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015" int __cdecl main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
int iResult;
int recvbuflen = DEFAULT_BUFLEN; // Validate the parameters
/* if (argc != 2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}*/ // Initialize Winsock
//The WSAStartup function is called to initiate use of WS2_32.dll.
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
} ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port
iResult = getaddrinfo("localhost", DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
} // Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) { // Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
} // Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
} freeaddrinfo(result); if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
} // Send an initial buffer
iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
if (iResult == SOCKET_ERROR) {
printf("send failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
} printf("Bytes Sent: %ld\n", iResult); // shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
} // Receive until the peer closes the connection
do { iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError()); } while( iResult > 0 ); // cleanup
closesocket(ConnectSocket);
WSACleanup(); return 0;
}

在windows下用C语言写socket通讯实例的更多相关文章

  1. windows下的go语言的环境搭建和初探

    闲话不说,直入主题. 1.准备工具 a.windows下的Go语言开发安装包 官方下载地址:https://code.google.com/p/go/downloads/list b.Go语言中文官网 ...

  2. Windows下用C语言连接Mysql注意问题

    原文:Windows下用C语言连接Mysql注意问题 环境是:在VS6.0 安装Mysql后,我们需要相应的头文件以及lib文件,所以安装过程必须是完整安装.否则不会生成include文件夹哦~ 具体 ...

  3. Windows下搭建go语言开发环境 以及 开发IDE (附下载链接)

    1.下载 并且 安装 Go安装包   =========================================================== 在CSDN上传了我的版本,供大家下载: = ...

  4. Windows下学习C语言有哪些集成开发软件?

    前言 初学者学习C语言遇到的最大困难想必就是搭建环境了,相当多的初学者就是被搭建环境导致放弃了学习编程,就我自己的经验而言,初学编程不应该受限于环境,使用成熟好用的环境就可以了,之后熟悉一些可以在慢慢 ...

  5. UNIX环境下用C语言写静态库与动态库

    静态库,动态库用UNIX 的术语来说,或者叫做归档文件(archive 常以.a 结尾)和共享对象(share object 常以lib 开头.so 结尾)更为准确.静态库,动态库可能是WINDOWS ...

  6. Linux环境下用C语言实现socket 通信---简单代码

    Socket编程实例: 服务器端:一直监听本机的8000号端口,如果收到连接请求,将接收请求并接收客户端发来的消息,并向客户端返回消息. 客户端:client.c /* File Name: clie ...

  7. windows下一个,OracleServiceXXX和Oracle 关系实例

    其实,windows下的oracle,在oracle实例启动时,是全然依赖于 window服务中的OracleServiceXXX .这个XXX就是oracle的实例名(注意啊,不是数据库名称,而是实 ...

  8. socket通讯实例与TCP/UDP的区别

    一.socket代码实例 1.简单的socket通讯: 服务端代码实例: import socket sock = socket.socket(socket.AF_INET, socket.SOCK_ ...

  9. 【Go】windows下搭建go语言编译环境

    主要是协助杨哥做Kubernetes相关工作,由于Kubernetes和Docker都是由Go语言编写,因此改源码后还是需要go语言编译器来编译运行.所以打算先在windows上安装一下go语言环境. ...

随机推荐

  1. java流的性能优化1-文件复制

    传统的I/O速度相对照较慢,它会成为系统性能的瓶颈,所以在java1.4之后提供了NIO,它是一种全新的流:它具有下面特性: 1.为全部的原是类型提供Buffer缓存支持: 2.使用java.nio. ...

  2. 默认情况下安装的应用程序C盘后提示权限不足,当你开始介意。。。

    最近,不少用户抱怨的经销商.正在使用win 7我们的计算机系统上安装软件后,提示权限不够开放系统,无法启动软件. 在xp该系统是没有问题的.原因是,我们会选择在默认安装路径系统C-disk.和win ...

  3. nginx源代码分析--读请求主体(1)

    首先,读取请求体已进入HTTP要求11相,我们需要做的请求正文部分处理一些模块,所以这个模块需要注册功能在这个阶段,在阅读功能要求的身体ngx_http_read_client_request_bod ...

  4. HDU3988-Harry Potter and the Hide Story(数论-质因数分解)

    Harry Potter and the Hide Story Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 ...

  5. React-Native入门指南之HelloWorld

    iOS React-Native入门指南之HelloWorld React-native 作为facebook开源项目,最近是火的一塌糊涂,它采用node.js能够写ios和android的nativ ...

  6. [ACM] poj 1088 滑雪 (内存搜索DFS)

    滑雪 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 73409   Accepted: 27141 Description ...

  7. Spring先进的交易管理困难剖析

    1Spring事务传播行为 所谓事务传播行为就是多个事务方法相互调用时,事务怎样在这些方法间传播.Spring支持7种事务传播行为 PROPAGATION_REQUIRED(增加已有事务) 假设当前没 ...

  8. Doug Lea

    如果IT的历史,是以人为主体串接起来的话,那么肯定少不了Doug Lea.这个鼻梁挂着眼镜,留着德王威廉二世的胡子,脸上永远挂着谦逊腼腆笑容,服务于纽约州立大学Oswego分校计算机科学系的老大爷. ...

  9. Object-c中间initialize 与 辛格尔顿

    简单说下initialize任务.在初始化过程中同样的类将被调用一次. 直接在代码解释initialize任务. 创建一个InitTest类 InitTest.m #import "Init ...

  10. 他的第一个NDK的Demo

    DEMO下载链接: http://download.csdn.net/detail/logicsboy/7535409 首先给你们恶补下啥是NDK:(我从百度Copy的) NDK全称:Native D ...