#include<Winsock2.h>
#include<stdio.h>
#pragma comment(lib,"Ws2_32.lib")
#include<stdlib.h>
void main()
{
WSADATA wsaData;//协议栈
struct sockaddr_in server, client;//服务端和客户端的地址
int iLen;
char recMessage[1024]; //接受字符串缓冲区
SOCKET sAccept;//连接上来的那个客户端套接口
memset(recMessage, 0, sizeof(recMessage));//将接收缓冲区内容全部变为0
printf("-------------------------\n");
printf("服务器在等待\n");
printf("-------------------------\n");
/*
检查协议栈是否加载成功
*/
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("协议栈加载失败!\n");
return;
}
//创建服务器端套接口
SOCKET sListen = socket(AF_INET, SOCK_STREAM, 0);
if (sListen == INVALID_SOCKET)
{
printf("sListen套接口创建失败!\n");
return;
}
//为server端地址赋值
server.sin_family = AF_INET;
server.sin_port = htons(8888);
server.sin_addr.s_addr = htonl(INADDR_ANY);
//将服务端地址和服务端socket套接口绑定到一起
if (bind(sListen, (LPSOCKADDR)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("绑定失败!\n");
return;
}
//开始监听
if (listen(sListen, 5) == SOCKET_ERROR)
{
printf("监听失败!\n");
return;
}
//客户端地址长度
iLen = sizeof(client);
while (1)
{
//得到连接上来的那个客户端套接口
sAccept = accept(sListen, (struct socketaddr*)&client, &iLen);
if (sAccept == INVALID_SOCKET)
{
printf("接受失败!");
break;
}
printf("接受的客户端的地址IP是:[%s], port[%d]\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
//接收数据
while (1)
{
//从这个客户端套接口上面接收信息
int recLen = recv(sAccept, recMessage, sizeof(recMessage), 0);
if (recLen == 0)
return;
else if (recLen == SOCKET_ERROR)
{
printf("接收失败!\n");
}
printf("沸沸腾:%s\n", recMessage);
}
}
closesocket(sAccept);//关闭套接口
closesocket(sListen);
WSACleanup();//清空协议栈
}
#include<Winsock2.h>
#include<stdio.h>
#pragma comment(lib,"Ws2_32.lib")
#include<stdlib.h>
void main()
{
WSADATA wsaData;//协议栈
struct sockaddr_in server;//server端的地址情况
SOCKET sClient;//客户端套接口
//加载协议栈
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("协议栈加载失败!\n");
return;
}
//初始化服务器端的地址,与端口情况
server.sin_family = AF_INET;
server.sin_port = htons(8888);
server.sin_addr.s_addr = inet_addr("172.17.152.206");
//创建一个tcp的套接口
sClient = socket(AF_INET, SOCK_STREAM, 0);
if (sClient == INVALID_SOCKET)
{
printf("套接口创建失败!\n");
return;
}
//向服务器端申请连接
if (connect(sClient, (struct sockaddr*)&server, sizeof(server)) == INVALID_SOCKET)
{
printf("连接失败!\n");
return;
}
for (int i = 0; i < 5; i++)
{
printf("田腾飞: ");
char message[1024];
gets_s(message,1024);
//向客户端套接口发送数据
int iSend = send(sClient, message, sizeof(message), 0);
if (iSend == SOCKET_ERROR)
{
printf("发送失败!\n");
break;
}
else if (iSend == 0)
break;
else
{
printf("发送成功!\n");
}
}
closesocket(sClient);//关闭套接口
WSACleanup();//清楚协议栈
}
原文地址:http://blog.csdn.net/ttf1993/article/details/45198579