使用协议UDP,仅实现简单的连接功能:
服务端:
#pragma comment(lib, "ws2_32.lib ")
#include <winsock2.h>
#include <stdio.h>
int main()
{
SOCKET socket1;
WSADATA wsaData;
int iErrorcode;
if(WSAStartup(MAKEWORD(2,2), &wsaData))
{
printf("Winsock can not be init!");
WSACleanup();
return 0;
}
printf("server begin to create socket!\n");
//struct sockaddr_in local;
//struct sockaddr_in from;
sockaddr_in local;
sockaddr_in from;
int fromlen = sizeof(from);
local.sin_addr.s_addr = INADDR_ANY;
local.sin_family = AF_INET;
local.sin_port = htons(5566);
socket1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
bind(socket1, (struct sockaddr *)&local, fromlen);
while(1)
{
char buffer[1024] = "\0";
printf("waiting message form client:");
if(SOCKET_ERROR != recvfrom(socket1,
buffer, sizeof(buffer), 0,
(struct sockaddr *)&from, &fromlen))
{
if(strcmp(buffer, "bye") == 0)
{
printf("client quit!\n");
break;
}
printf("recieve message form %s -- %s \n",
inet_ntoa(from.sin_addr), buffer);
sendto(socket1, buffer, sizeof(buffer),
0, (struct sockaddr *)&from, fromlen);
}
}
closesocket(socket1);
return 0;
}
客户端:
#pragma comment(lib, "ws2_32.lib ")
#include <winsock2.h>
#include <stdio.h>
int main()
{
SOCKET socket1;
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2,2), &wsaData))
{
printf("can not init !\n");
WSACleanup();
return 0;
}
printf("client begin to create socket!\n");
struct sockaddr_in server;
int len = sizeof(server);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5566);
server.sin_family = AF_INET;
socket1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP );
while(1)
{
char buffer[1024] = "\0";
printf("input message: ");
scanf("%s", buffer);
if(strcmp(buffer, "bye") == 0)
{
sendto(socket1, "bye", 3 * sizeof(char), 0,
(struct sockaddr *)&server, len);
printf("exit!\n");
Sleep(100);
closesocket(socket1);
break;
}
if(SOCKET_ERROR != sendto(socket1, buffer, sizeof(buffer),
0, (sockaddr *)&server, len))
{
Sleep(100);
if(recvfrom(socket1, buffer, sizeof(buffer), 0, (struct sockaddr *)&server, &len) != SOCKET_ERROR)
{
printf("recieve from server : %s \n", buffer);
}
}
}
closesocket(socket1);
return 0;
}