TCP实现点对点聊天-服务器端
#include <stdio.h>
#include <winsock2.h>
int main(int argc, char *argv[])
{
int nclients = 0;
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if(WSAStartup(sockVersion, &wsaData) != 0)
{
return 0;
}
SOCKET listensocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(listensocket == INVALID_SOCKET)
{
printf("创建socket失败!!!");
return 0;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(8888);
server.sin_addr.S_un.S_addr = INADDR_ANY;
if(bind(listensocket, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("绑定地址失败!");
return 0;
}
if(listen(listensocket, 6) == SOCKET_ERROR)
{
printf("监听失败!");
return 0;
}
SOCKET clientsocket;
struct sockaddr_in clientaddr;
int nclientaddrlen = sizeof(clientaddr);
char recvData[256];
printf("等待连接!!");
clientsocket = accept(listensocket, (struct sockaddr *)&clientaddr, &nclientaddrlen);
if(clientsocket == INVALID_SOCKET)
{
printf("接收客户端连接错误!");
return 0;
}
printf("客户端%s连接成功!", inet_ntoa(clientaddr.sin_addr));
while(1)
{
int ret = recv(clientsocket, recvData, 256, 0);
if(ret > 0)
{
recvData[ret] = '\0';
printf(recvData);
}
memset(recvData, 0, sizeof(recvData));
nclients++;
char sendData[256];
sprintf(sendData, "您好,第%03d号客户\n", nclients);
send(clientsocket, sendData, strlen(sendData), 0);
memset(sendData, 0, sizeof(sendData));
}
closesocket(clientsocket);
closesocket(listensocket);
WSACleanup();
return 0;
}
TCP实现点对点聊天-客户端
#include <stdio.h>
#include <winsock2.h>
int main(int argc, char *argv[])
{
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if(WSAStartup(sockVersion, &wsaData))
{
return 0;
}
SOCKET clientsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(clientsocket == INVALID_SOCKET)
{
printf("socket创建错误!");
return 0;
}
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(8888);
serveraddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int len = sizeof(serveraddr);
if(connect(clientsocket, (struct sockaddr*)&serveraddr, len) == SOCKET_ERROR)
{
printf("连接服务器失败!");
closesocket(clientsocket);
return 0;
}
while(1)
{
char sendData[20];
gets(sendData);
sendData[strlen(sendData)] = '\n';
send(clientsocket, sendData, strlen(sendData), 0);
memset(sendData, 0, sizeof(sendData));
char recvData[256];
int ret = recv(clientsocket, recvData, 256, 0);
if(ret > 0)
{
recvData[ret] = '\0';
printf("服务器回应:%s", recvData);
}
memset(recvData, 0, sizeof(recvData));
}
clockscket(clientsocket);
WSACleanup();
return 0;
}
|