在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通讯实例的更多相关文章
- windows下的go语言的环境搭建和初探
闲话不说,直入主题. 1.准备工具 a.windows下的Go语言开发安装包 官方下载地址:https://code.google.com/p/go/downloads/list b.Go语言中文官网 ...
- Windows下用C语言连接Mysql注意问题
原文:Windows下用C语言连接Mysql注意问题 环境是:在VS6.0 安装Mysql后,我们需要相应的头文件以及lib文件,所以安装过程必须是完整安装.否则不会生成include文件夹哦~ 具体 ...
- Windows下搭建go语言开发环境 以及 开发IDE (附下载链接)
1.下载 并且 安装 Go安装包 =========================================================== 在CSDN上传了我的版本,供大家下载: = ...
- Windows下学习C语言有哪些集成开发软件?
前言 初学者学习C语言遇到的最大困难想必就是搭建环境了,相当多的初学者就是被搭建环境导致放弃了学习编程,就我自己的经验而言,初学编程不应该受限于环境,使用成熟好用的环境就可以了,之后熟悉一些可以在慢慢 ...
- UNIX环境下用C语言写静态库与动态库
静态库,动态库用UNIX 的术语来说,或者叫做归档文件(archive 常以.a 结尾)和共享对象(share object 常以lib 开头.so 结尾)更为准确.静态库,动态库可能是WINDOWS ...
- Linux环境下用C语言实现socket 通信---简单代码
Socket编程实例: 服务器端:一直监听本机的8000号端口,如果收到连接请求,将接收请求并接收客户端发来的消息,并向客户端返回消息. 客户端:client.c /* File Name: clie ...
- windows下一个,OracleServiceXXX和Oracle 关系实例
其实,windows下的oracle,在oracle实例启动时,是全然依赖于 window服务中的OracleServiceXXX .这个XXX就是oracle的实例名(注意啊,不是数据库名称,而是实 ...
- socket通讯实例与TCP/UDP的区别
一.socket代码实例 1.简单的socket通讯: 服务端代码实例: import socket sock = socket.socket(socket.AF_INET, socket.SOCK_ ...
- 【Go】windows下搭建go语言编译环境
主要是协助杨哥做Kubernetes相关工作,由于Kubernetes和Docker都是由Go语言编写,因此改源码后还是需要go语言编译器来编译运行.所以打算先在windows上安装一下go语言环境. ...
随机推荐
- WWDC2014开源
A Cocoa OSX App to help you download WWDC2014 videos 地址:https://github.com/iosxtools/WWDC2014 版权声明:本 ...
- YUV摘要格式
始终保持视频数据YUV联系,因为基于其产品的组织不同的公司格不同的类型定义,派生出多种不同YUV格公式. 大体,YUV从在点的形式的像素组织中,有两个:1.planer状态.2.packet状态. p ...
- 采用CSS3 Media Query技术适应Android平板屏幕分辨率和屏幕像素密度
采用HTML5在开发移动应用程序满足各种需求Android分辨率和屏幕的平板设备密度,这是非常麻烦的过程,最终的解决方案是使用css media query,匹配相同的时间分辨率和屏幕像素密度.上进行 ...
- [Unity3D]Unity3D游戏开发3D选择场景中的对象,并显示轮廓效果强化版
大家好,我是秦培,欢迎关注我的博客,我的博客地址blog.csdn.net/qinyuanpei. 在上一篇文章中,我们通过自己定义着色器实现了一个简单的在3D游戏中选取.显示物体轮廓的实例. 在文章 ...
- Visual Studio Team Services使用教程--添加团队成员
- Swift 学习Using Swift mix and match, network: 写rss读者
有使用第三方库.因此,需要使用mix and match财产. 请指出错误,谢谢! rss 阅读器,非常easy的代码.仅仅是为了学习swift语言而写. 1、BaseViewController.s ...
- unix您不能使用crontab设置运营计划
unix您不能使用crontab设置运营计划 在系统中进行crontab例如,设置在下列现象时有发生: 解决方法: 编辑cron文件内容: #EDITOR=vi #export EDITOR ...
- 使用Advanced Installer将.exe程序重新封装为.msi程序
原文:使用Advanced Installer将.exe程序重新封装为.msi程序 使用Advanced Installer将.exe程序重新封装为.msi程序 首先安装Advanced instal ...
- 注解配置的Spring MVC
基于注解配置的Spring MVC 简单的HelloWorld实例应用 2.1 问题 使用注解的方式重构helloworld应用案例. 2.2 方案 1. @RequestMapping注解应用 ...
- Java多线程的~~~synchronized加入参数,以实现独立片段
有时候,我们不希望在整个方法的前面加上synchronized这个keyword.这将使整个方法调用变得缓慢,我们只是重点 代码的地方添加这个synchronized这个keyword,然后这样就能加 ...