假设服务端的IP为w.x.y.z, 下面来写一个简单的聊天程序:
服务端为;
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup( wVersionRequested, &wsaData );
SOCKET sockSrv=socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("w.x.y.z"); // 请将w.x.y.z改为实际IP
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8888);
bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
char recvBuf[100];
char sendBuf[100];
char tempBuf[100];
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
while(1)
{
recvfrom(sockSrv, recvBuf, 100, 0, (SOCKADDR*)&addrClient, &len);
sprintf(tempBuf,"%s", recvBuf);
printf("%s\n", tempBuf);
printf("Please input data:\n");
gets(sendBuf);
sendto(sockSrv, sendBuf, strlen(sendBuf) + 1, 0, (SOCKADDR*)&addrClient, len);
}
closesocket(sockSrv);
WSACleanup();
return 0;
}
客户端为:
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(wVersionRequested, &wsaData);
SOCKET sockClient = socket(AF_INET, SOCK_DGRAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("w.x.y.z"); // 请将w.x.y.z改为实际IP
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(8888);
char recvBuf[100];
char sendBuf[100];
char tempBuf[100];
int len=sizeof(SOCKADDR);
while(1)
{
printf("Please input data:\n");
gets(sendBuf);
sendto(sockClient, sendBuf, strlen(sendBuf) + 1, 0, (SOCKADDR*)&addrSrv, len);
recvfrom(sockClient,recvBuf, 100, 0, (SOCKADDR*)&addrSrv, &len);
sprintf(tempBuf,"%s", recvBuf);
printf("%s\n", tempBuf);
}
closesocket(sockClient);
WSACleanup();
return 0;
}
先启动服务端,再启动客户端,运行程序,可以相互聊天。