// client.cpp : 定义控制台应用程序的入口点。
//
//添加 ws2_32.lib链接库
#include "stdafx.h"
#include <stdio.h>
#include <Winsock2.h>
void main()
{
SOCKET socket1;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 1), &wsaData)) //调用Windows Sockets DLL
{
printf("Winsock无法初始化!\n");
WSACleanup();
return;
}
struct sockaddr_in server;
int len = sizeof(server);
server.sin_family = AF_INET;
server.sin_port = htons(27015); ///server的监听端口
server.sin_addr.s_addr = inet_addr("127.0.0.1"); ///server的地址
printf("connect the server...\n");
socket1 = socket(AF_INET, SOCK_DGRAM, 0);
while (1)
{
char buffer[1024] = "\0";
printf("input message\n");
scanf("%s", buffer);
if (strcmp(buffer, "bye") == 0)
{
printf("exit\n");
Sleep(100);
closesocket(socket1);
break;
}
if (sendto(socket1, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, len) != SOCKET_ERROR)
{
Sleep(100);
if (recvfrom(socket1, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, &len) != SOCKET_ERROR)
printf("echo from server:%s\n", buffer);
}
}
}
//
//添加 ws2_32.lib链接库
#include "stdafx.h"
#include <stdio.h>
#include <Winsock2.h>
void main()
{
SOCKET socket1;
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 1), &wsaData)) //调用Windows Sockets DLL
{
printf("Winsock无法初始化!\n");
WSACleanup();
return;
}
struct sockaddr_in server;
int len = sizeof(server);
server.sin_family = AF_INET;
server.sin_port = htons(27015); ///server的监听端口
server.sin_addr.s_addr = inet_addr("127.0.0.1"); ///server的地址
printf("connect the server...\n");
socket1 = socket(AF_INET, SOCK_DGRAM, 0);
while (1)
{
char buffer[1024] = "\0";
printf("input message\n");
scanf("%s", buffer);
if (strcmp(buffer, "bye") == 0)
{
printf("exit\n");
Sleep(100);
closesocket(socket1);
break;
}
if (sendto(socket1, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, len) != SOCKET_ERROR)
{
Sleep(100);
if (recvfrom(socket1, buffer, sizeof(buffer), 0, (struct sockaddr*)&server, &len) != SOCKET_ERROR)
printf("echo from server:%s\n", buffer);
}
}
}